4

How to select more than one option in the multiple selection list using jquery?

 2 years ago
source link: https://www.codesd.com/item/how-to-select-more-than-one-option-in-the-multiple-selection-list-using-jquery.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to select more than one option in the multiple selection list using jquery?

advertisements

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!!!


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");
});

Tags jquery

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK