0

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!

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

Please try below code :-

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.