开发者

Jquery - Setting form select-field "selected" value only works after refresh

I want to use a form select-field for users to select their country of residence, which shows the IP based country as default value (plus the IP address next to it);

Location info (ipinfodb.com) is working. I'm passing "country" and "ip" to the function, which should modify select-field and ip adress

Problem: IP adress works, but the select-field only updates after I hit refresh.

Can someone tell me why?

Here is the code:

HTML

<select name="setup_changeCountry" id="setup_changeCountry">
     <option value="AL-Albania">Albanien</option>
     <option value="AD-Andorra">Andorra</option>
     <option value="AM-Armenia">Armenien</option>
     <option value="AU-Australia">Australien</option>
     ...
</select>
<div class="setup_IPInfo">
    <span>Your IP</span>
    <span class="ipAdress"> -- ip --</span>
</div>

Javascript/Jquery

fu开发者_如何转开发nction morph(country,ip) >> passed from function, called on DOMContentLoaded
{
var ipAdress = ip;
$('.ipAdress').text(ipAdress);

var countryForm = country; 
$('#setup_changeCountry  option').each(function()
    {
    if ($(this).val().substr(0,2) == countryForm)
        {
        $(this).attr('selected', "true");
        }
    });
} 

Thanks for any clues on how to fix this.

Frequent


you can simplify your loop immensely and let jQuery do the work:

$("#setup_changeCountry option[value$='" + country + "']").attr('selected', true);

make sure:

  • the case matches (your country must then also begin with a capital letter)
  • you execute this code after the DOM's loaded, otherwise you might be trying to select an option that doesnt exist yet


It's selected="selected" not selected="true", therefore:

$(this).attr('selected', 'selected');

(Also you could skip the var ipAdress and just pass ip in the next line)


you should use:

 $(document).ready(name_of_function);

this way you can run the function to select the country. You can use this function for that:

function morph(country,ip){
    var ipAdress = ip;
    $('.ipAdress').text(ipAdress);
    var countryForm = country; 
    $("#setup_changeCountry option[value$='" + country + "']").attr('selected', true);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜