Reputation:
In my web application a method returns a list of array contains ID's of select options which should have to be selected. Its is hard to make them all selected using DOM methods.
Is there any way to do it using jQuery.
Any suggestions would be more appreciative...
Thanks in Advance!!!
Upvotes: 4
Views: 1376
Reputation: 322592
EDIT: Based on your comment below, your data looks the code below.
There's a problem. It is not valid for an HTML ID attribute to start with a number. IDs must begin with a letter.
I'll show you the solution anyway, but you should fix the IDs.
var array = [{respID:1, respName:null},
{respID:2, respName:null},
{respID:3, respName:null},
{respID:4, respName:null},
{respID:5, respName:null}
];
$.each(array, function(i,val) {
$('#' + val.respID).attr("selected", "selected");
});
Now this will give you the value of respID
in each iteration of the loop.
But again, HTML IDs can not start with a number. I'd suggest updating your HTML ID attributes to something like id_5
instead of 5
.
<select>
<option id="id_1" value="some value">some text</option>
<option id="id_2" value="some value">some text</option>
<option id="id_3" value="some value">some text</option>
...
</select>
Then you would do this:
$.each(array, function(i,val) {
$('#id_' + val.respID).attr("selected", "selected");
});
Upvotes: 2
Reputation: 6723
If ids is an array of IDs, the following code should work:
$.each(ids, function() { $("#" + this).attr("selected", true); });
Upvotes: 1
Reputation: 72230
It's actually quite simple, all you need to do is add an attribute of selected to the elements you want.
$("#id1, #id2", "select").attr("selected", "selected");
You can filter them by value too
$("option[value=someText]", "select").attr("selected", "selected");
Upvotes: 1
Reputation: 344753
Using jQuery, you can just call attr("selected", true)
on the collection of elements. All you have to do is get the selector right:
$('#opt1, #opt2, #opt3').attr("selected", true);
Upvotes: 4