have an array of values [1,2,4] representing the values of a multi-select box, how do i set them as selected using either jquery or plain javascript?
thanks for your help.
jQuery has a utility called $.inArray(value,array)
. You could 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. That's why you need to test for >= 0
.
View example here-
http://jsfiddle.net/PJs37/
In plain 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 JavaScript function in_array that mimic the PHP one...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With