8

I have a country dropdown and I set the selected attribute to US. I can clearly see select="selected" into select OPTION having value US in firebug. But neither firefox or chrome shown US as selected. I have code for populate & 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 it is really possible for any reason to browser not shown the selected even we set the attribute selected.

UPDATE : Ok guys, As I was expecting it must be conflicted by other code. And that is the case . I am using bootstrapValidator and a special call "resetForm" which did this behavior. However one thing I did not understand why still html select in firebug shown selected attribute ? But at last I placed this code after resetForm call. Thanks to all for suggestions & help.

kuldeep.kamboj
  • 2,566
  • 3
  • 26
  • 63

5 Answers5

10

I had this peculiar problem of multiple select not selecting the selected values. What I ended up doing is select them with JS (I have jQuery in my app, so that makes it easier) like so:

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

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

Gogol
  • 3,033
  • 4
  • 28
  • 57
3

you dont need to set selected="selected", selected itself is sufficient

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

Also check, is your HTML markup is correct. You are closing the <option> with </value>. It is wrong, should be <option></option>

EDIT

If the above solution is not working, you could set it through JavaScript:

document.getElementById("idOfSelect").selectedIndex = "1";//index starts from 0
Nishad K Ahamed
  • 1,374
  • 15
  • 25
2

This works for me but you can try this:

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

xatzistnr
  • 174
  • 1
  • 7
1

you don't need selected="selected" just value.id + ' selected>' + ... also it should be not lastly, check that

defaultValue == value.id

in the debugger.

Andrew Luo
  • 919
  • 1
  • 5
  • 6
0

I had a similar issue but in my case it was not JS, but the GET variable value of another option matched the name of an option and that didn't work.

So: https://example.com?section=instruments&instruments=0 failed. Renaming to unique names fixed it for me.

E Allison
  • 51
  • 6