简体   繁体   中英

how to set selected attribute in option for select drop down list

here is the html code

<select id="privacy" onChange="run()">
   <option value="1" selected="selected" >public</option>
   <option value="2">contact</option>
</select>

for value=2, im selecting contact and this contact is appended in the list but its not showing as selected.below is the jquery code for appending but im not getting where to set this selected atrribute.

$('#privacy').append($('<option> ', {
          text: postcontact
}));

USe selected attribute like this way

$('#privacy').append($('<option> ', {
    text: "postcontact",
    selected: "selected"
}));

Try to use chaining at this context ,

$('#privacy').append($('<option> ', {text: postcontact ,value:2})).val(2);

or try this

$('#privacy').find("option").removeAttr("selected").end().append($('<option> ', {text: "postcontact" ,value:3,selected: "selected"})).val(3);

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