Dynamically select multiple options in the selection window

have an array of values ​​[1,2,4] representing the values ​​of the multiple choice field, how to set them as selected using jquery or simple javascript?

thanks for your help.

+4
source share
4 answers

In simple JavaScript:

function in_array(needle, haystack, argStrict) { var key = '', strict = !!argStrict; if (strict) { for (key in haystack) { if (haystack[key] === needle) return true; } } else { for (key in haystack) { if (haystack[key] == needle) return true; } } return false; } var values = new Array(1, 2, 4); var select = document.getElementById('selectName'); //Change to the id of the select if (select) { for (var i = 0; i < select.options.length; i++) { //Select options matching array values, unselect others select.options[i].selected = in_array(select.options[i].value, values, false); } } 

UPDATE: Added in_array JavaScript function that mimics PHP one ...

+3
source

jQuery has a utility called $.inArray(value,array) . You can do something like this:

 var array = [1,2,4]; $('#example option').each(function() { var $th = $(this); var value = parseInt($th.val()); if( $.inArray(value,array) >= 0 ) { $th.attr('selected','selected'); } }); 

$.inArray() returns the index of the value if it is found, or -1 if it is not in the array. This is why you need to test >= 0 .

See an example here -

http://jsfiddle.net/PJs37/

+6
source

Since I don’t have 50 repeat points yet, I can not comment or correct the post above

So here is my fix for the specified array

 var values = new Array(1, 2, 4); // using commas var values = [1, 2, 4]; // using array notation 
+1
source

I am not very familiar with Javascript, but I think this is:

 var values = [1, 2, 4]; var sel = document.getElementsByTagName('SELECT')[0]; for (var i = 0; i < sel.options.length; i++) { if(sel.options[i].value == 1 || sel.options[i].value == 2 || sel.options[i].value == 4) sel.options[i].selected = 'selected'; } 
0
source

Source: https://habr.com/ru/post/1308049/


All Articles