Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically select multiple options in a select box

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.

like image 272
Shah Avatar asked Jan 23 '23 04:01

Shah


2 Answers

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/

like image 177
user113716 Avatar answered Jan 24 '23 17:01

user113716


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

like image 30
AlexV Avatar answered Jan 24 '23 17:01

AlexV