开发者

jQuery - Check Select Value on Refresh?

Please excuse the newbie code, im new. Any coding tips are much appreciated as well of course.

Here's the Problem:

This code seems to work fine, if I first load the page, USA is selected and States is visible. If I then select another country, the states disappear as they should...

However, if I then hit the Refresh Button, states become visible again but the country select stays what it is (not USA).

How can I protect myself from this?

#stateWrapper { display: 开发者_如何学Goblock; }

#country USA is set to "selected"

$('#country').click(function(){
    var selectedValue = $("select").val();

    if(selectedValue == 'US') {
        $('#stateWrapper').attr('style', 'display: block;');            
    }else{
        $('#stateWrapper').attr('style', 'display: none;');
    }

    if(selectedValue == 'CA') {
        $('#provinceWrapper').attr('style', 'display: block;');         
    }else{
        $('#provinceWrapper').attr('style', 'display: none;');
    }
});

I know one workaround is to changed USA from "selected" to something else generic like "Please Select Country". But I would prefer the convenience that the user doesnt need to select USA when 90% of the customers will be from the states. Plus I would really like to solve a problem rather than working around it for once...


beacause your controll is wrapped into a click event. Refreshing the page isn't a click event.

you need to use you control has a function

function check_country()
{
   //your code above
}

and the into the document ready you call

check_country();

alone and then you have to bind the function to the click event

$('#country').click(function(){check_country();}

so now your control function works both on page load and on click

at last you should have something like that:

function check_country()
{
    var selectedValue = $("select").val();

    if(selectedValue == 'US') {
        $('#stateWrapper').attr('style', 'display: block;');            
    }else{
        $('#stateWrapper').attr('style', 'display: none;');
    }

    if(selectedValue == 'CA') {
        $('#provinceWrapper').attr('style', 'display: block;');         
    }else{
        $('#provinceWrapper').attr('style', 'display: none;');
    }
}

$(document).ready(function()
{
   check_country();
   $('#country').click(function(){check_country();});
});


One way of handling this would be to use the jQuery.ready() method to execute your function when the page loads as well as when the user clicks. First pull your code into a function definition:

function update_states() {
   //state updating code goes here
}

Then add the following code to call that function when the page is loaded or refreshed:

$(function() {update_states();})

And to run it when updated as you were already doing:

$('#country').click(function() {update_states();})

Does this achieve what you were looking to do?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜