Html select not show selected even after selected set

I have a country dropdown and I selected the selected attribute for US. I can clearly see select = "selected" in select OPTION with US value in firebug. But neither Firefox nor Chrome showed the US as the chosen one. I have a code to fill in and selected country as follows.

var countryData = getCountryData();
var html = '<option value="">Select Country</option>'; 
$.each(countryData, function(key,value) {
    if(defaultValue == value.id)
    {
        html = html + '<option value="'+value.id+'" selected="selected">'+value.name+'</option>';
    }
    else
    {
        html = html + '<option value="'+value.id+'">'+value.name+'</option>';
    }
});
countryField.html(html);

      

If for some reason, for whatever reason, the browser is not shown, the selected even we have set the selected attribute.

UPDATE: Ok guys. As I expected this should be conflicting with other code. And so it is. I am using bootstrapValidator and a custom "resetForm" call that did this. Be that as it may, I didn't understand why else the html select in firebug displays the selected attribute? But finally I put this code after the resetForm call. Thanks everyone for the suggestions and help.

+3


source to share


4 answers


you don't need to install selected="selected"

, yourselfselected

<option value="anything" selected>anything</option>

      

Also check if your HTML markup is correct. You close <option> with </value>

. It must be wrong<option></option>



EDIT

If the above solution doesn't work, you can install it via JavaScript:

document.getElementById("idOfSelect").selectedIndex = "1";//index starts from 0

      

+3


source


This works for me, but you can try this:



countryField.html(html).trigger('change');

+2


source


you don't need selected = "selected" just value.id + 'selected>' + ... also it shouldn't be finally, make sure

defaultValue == value.id

      

in the debugger.

+1


source


I had this specific problem of multiple choice not picking selected values. What I ended up doing was to select them using JS (I have jQuery in my app to make this easier):

$('#select_element').find('option[selected="selected"]').each(function(){
    $(this).prop('selected', true);
});

      

I know this is ugly and should be avoided, but if nothing else works, this will work.

0


source







All Articles