Alireza Fattahi
Alireza Fattahi

Reputation: 45515

Dynamic setting of html options of a select box does not appear in select html

We can dynamically mark some options with jquery

With below select:

<select name='strings' id="strings" multiple style="width:100px;">
    <option value="Test">Test</option>
    <option value="Prof">Prof</option>
    <option value="Live">Live</option>
    <option value="Off">Off</option>
    <option value="On">On</option>
</select>

The below js will select Test,Prof,Off

var values="Test,Prof,Off";
$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").prop("selected", true);
});

console.log( $("#strings").html() ); 

http://jsfiddle.net/3f0ea4dc/

This works fine ...

But the $("#strings").html() does not mark options as selected. So I expected to see

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

But I see

  <option value="Test">Test</option>.

Any comments ?! Is there any way I can get the html with selected!

Upvotes: 0

Views: 40

Answers (2)

Anand Systematix
Anand Systematix

Reputation: 632

Please try below code :-

$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").attr("selected", true);
});

http://jsfiddle.net/3f0ea4dc/3/

Upvotes: 1

Steeve Pitis
Steeve Pitis

Reputation: 4443

Just replace prop() by attr() it will work as expected ;)

Upvotes: 2

Related Questions