How to select more than one option in multiple select lists using jquery?

In my web application, the method returns a list of arrays containing the identifier of the selected options to be selected. It’s hard to make them all be selected using the DOM methods.

Is there any way to do this using jQuery.

Any suggestions would be more valuable ...

Thanks in advance!

+4
source share
4 answers

EDIT: Based on your comment below, your data is as follows.

There is a problem. The HTML ID attribute must not begin with a number. Identifiers must begin with a letter.

I will show you the solution anyway, but you have to fix the identifiers.

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 respID value in each iteration of the loop.

But then again, HTML identifiers cannot begin with a number. I suggest updating your HTML attributes to about 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 will do the following:

 $.each(array, function(i,val) { $('#id_' + val.respID).attr("selected", "selected"); }); 
+2
source

Using jQuery, you can simply call attr("selected", true) in the collection of elements. All you have to do is select the right selector:

 $('#opt1, #opt2, #opt3').attr("selected", true); 

http://api.jquery.com/attr/

+4
source

This is actually quite simple, all you have to do is add the attribute of the selected elements that you want.

 $("#id1, #id2", "select").attr("selected", "selected"); 

You can also filter them by value.

 $("option[value=someText]", "select").attr("selected", "selected"); 
+1
source

If the identifiers are an array of identifiers, the following code should work:

 $.each(ids, function() { $("#" + this).attr("selected", true); }); 
+1
source

All Articles