开发者

dynamically select multiple options in a select box

开发者 https://www.devze.com 2022-12-28 18:29 出处:网络
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?

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


I'm not very familiar with Javascript, but i think it's this:

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

精彩评论

暂无评论...
验证码 换一张
取 消