简体   繁体   中英

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

function 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 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);
}

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM