使用 Javascript 在多选中设置选定索引

发布于 2024-12-18 19:04:44 字数 1727 浏览 1 评论 0原文

我不确定为什么这不起作用,并且希望得到一些帮助!是的,我看过this

我尝试使用保存我想要选择的值的数组来设置选择元素中的多个选项,并通过数组和选择元素中的选项进行交互。请查找下面的代码:

// value is the array.
for (var j = 0; j < value.length; j++) {
    for (var i = 0; i < el.length; i++) {
        if (el[i].text == value[j]) {
            el[i].selected = true;
            alert("option should be selected");
        }
    }
}

完成这些循环后,即使alert() 触发,也不会选择任何内容。

欢迎任何想法!

谢谢

CM

PS(不确定代码格式发生了什么)。

编辑:完整功能

    if (CheckVariableIsArray(value) == true) {
        if (value.length > 1) { // Multiple selections are made, not just a sinle one.
            var checkBoxEl = document.getElementById(cbxElement);
            checkBoxEl.checked = "checked";
            checkBoxEl.onchange(); // Call function to change element to a multi select
            document.getElementById(element).onchange(); // Repopulates elements with a new option list.
            for (var j = 0; j < value.length; j++) {
                for (var i = 0; i < el.length; i++) {
                    if (el[i].text === value[j]) {
                        el[i].selected = true;
                        i = el.length + 1;
                    }
                }
            }
            //document.getElementById(element).onchange();
        }
    }
    else {
        for (var i = 0; i < el.length; i++) {
            if (el[i].innerHTML == value) {
                el.selectedIndex = i;
                document.getElementById(element).onchange();
            }
        }
    }

Im not sure why this isnt working and would love some help with it! And yes i have looked at this

Im trying to set multiple options in a select element as selected using an array holding the values i want selected and interating through both the array and the options in the select element. Please find code below:

// value is the array.
for (var j = 0; j < value.length; j++) {
    for (var i = 0; i < el.length; i++) {
        if (el[i].text == value[j]) {
            el[i].selected = true;
            alert("option should be selected");
        }
    }
}

After completing these loops nothing is selected, even though the alert() fires.

Any ideas are welcome!

Thanks

CM

PS (not sure whats happened to the code formatting).

EDIT: Full function

    if (CheckVariableIsArray(value) == true) {
        if (value.length > 1) { // Multiple selections are made, not just a sinle one.
            var checkBoxEl = document.getElementById(cbxElement);
            checkBoxEl.checked = "checked";
            checkBoxEl.onchange(); // Call function to change element to a multi select
            document.getElementById(element).onchange(); // Repopulates elements with a new option list.
            for (var j = 0; j < value.length; j++) {
                for (var i = 0; i < el.length; i++) {
                    if (el[i].text === value[j]) {
                        el[i].selected = true;
                        i = el.length + 1;
                    }
                }
            }
            //document.getElementById(element).onchange();
        }
    }
    else {
        for (var i = 0; i < el.length; i++) {
            if (el[i].innerHTML == value) {
                el.selectedIndex = i;
                document.getElementById(element).onchange();
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨巷深深 2024-12-25 19:04:44

对我有用。您是否正确设置 el 和 value ?您确定要查看每个选项的 innerHTML 而不是它的 value 属性吗?

请参阅 jsFiddle


HTML:

<select id="pick_me" multiple="multiple">
    <option>Hello</option>
    <option>Hello</option>
    <option>Foo</option>
    <option>Bar</option>
</select>

JS:

var value = ['Foo', 'Bar'],
    el = document.getElementById("pick_me");

// value is the array.
for (var j = 0; j < value.length; j++) {
    for (var i = 0; i < el.length; i++) {
        if (el[i].innerHTML == value[j]) {
            el[i].selected = true;
            //alert("option should be selected");
        }
    }
}

Works for me. Are you setting el and value correctly? And are you sure you want to look at each option's innerHTML instead of it's value attribute?

See the jsFiddle.


HTML:

<select id="pick_me" multiple="multiple">
    <option>Hello</option>
    <option>Hello</option>
    <option>Foo</option>
    <option>Bar</option>
</select>

JS:

var value = ['Foo', 'Bar'],
    el = document.getElementById("pick_me");

// value is the array.
for (var j = 0; j < value.length; j++) {
    for (var i = 0; i < el.length; i++) {
        if (el[i].innerHTML == value[j]) {
            el[i].selected = true;
            //alert("option should be selected");
        }
    }
}
若水般的淡然安静女子 2024-12-25 19:04:44

好吧,首先,你必须设置html select控件的multiple属性,像这样“”,然后你可以使用javascript函数SetMultiSelect(定义如下)设置选择html控件:

function SetMultiSelect(multiSltCtrl, values)
{
    //here, the 1th param multiSltCtrl is a html select control or its jquery object, and the 2th param values is an array
    var $sltObj = $(multiSltCtrl) || multiSltCtrl;
    var opts = $sltObj[0].options; //
    for (var i = 0; i < opts.length; i++)
    {
        opts[i].selected = false;//don't miss this sentence
        for (var j = 0; j < values.length; j++)
        {
            if (opts[i].value == values[j])
            {
                opts[i].selected = true;
                break;
            }
        }
    }
    $sltObj.multiselect("refresh");//don't forget to refresh!
}

$(document).ready(function(){
    SetMultiSelect($sltCourse,[0,1,2,3]);
});

Well, first of all, you must set the html select control multiple property, something like this "<select multiple="multiple">...</select>", and then you can use the javascript function SetMultiSelect (defined as below) to set the select html control:

function SetMultiSelect(multiSltCtrl, values)
{
    //here, the 1th param multiSltCtrl is a html select control or its jquery object, and the 2th param values is an array
    var $sltObj = $(multiSltCtrl) || multiSltCtrl;
    var opts = $sltObj[0].options; //
    for (var i = 0; i < opts.length; i++)
    {
        opts[i].selected = false;//don't miss this sentence
        for (var j = 0; j < values.length; j++)
        {
            if (opts[i].value == values[j])
            {
                opts[i].selected = true;
                break;
            }
        }
    }
    $sltObj.multiselect("refresh");//don't forget to refresh!
}

$(document).ready(function(){
    SetMultiSelect($sltCourse,[0,1,2,3]);
});
猥琐帝 2024-12-25 19:04:44

遇到这个问题并对答案不满意。
这是一个通用的非 jQuery 版本。它尽可能使用 Array.indexOf ,但如果不可用,则退回到 foreach 循环。

将一个节点与值数组一起传递到函数中。如果传入无效元素,将引发异常。这使用 === 来检查该值。大多数情况下,请确保将选项的值与字符串数组进行比较。

例如 selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );

var selectValues = (function() {

    var inArray = ( function() {

        var returnFn;

        if( typeof Array.prototype.indexOf === "function" ) {

            returnFn = function(option, values) {

                return values.indexOf( option.value ) !== -1;

            };

        } else {

            returnFn = function(option, values) {

                var i;

                for( i = 0; i < values.length; i += 1 ) {

                    if( values[ i ] === option.value ) {

                        return true;

                    }

                }

                return false;

            }

        }

        return returnFn;

    }() );

    return function selectValues(elem, values) {

        var 
            i,
            option;

        if( typeof elem !== "object" || typeof elem.nodeType === "undefined" )
            throw 'selectValues() expects a DOM Node as it\'s first parameter, ' + ( typeof elem ) + ' given.';

        if( typeof elem.options === "undefined" ) 
            throw 'selectValues() expects a <select> node with options as it\'s first parameter.';

        for( i = 0; i < elem.options.length; i += 1 ) {

            option = elem.options[ i ];

            option.selected = inArray( option, values );

        }

    }

}());

Ran into this question and wasn't satisfied with the answers.
Here's a generic, non-jQuery version. It utilises Array.indexOf where possible, but falls back to a foreach loop if it isn't available.

Pass a node into the function, alongside an array of values. Will throw an exception if an invalid element is passed into it. This uses === to check against the value. For the most part, make sure you're comparing the option's value to an array of strings.

E.g. selectValues( document.getElementById( 'my_select_field' ), [ '1', '2', '3'] );

var selectValues = (function() {

    var inArray = ( function() {

        var returnFn;

        if( typeof Array.prototype.indexOf === "function" ) {

            returnFn = function(option, values) {

                return values.indexOf( option.value ) !== -1;

            };

        } else {

            returnFn = function(option, values) {

                var i;

                for( i = 0; i < values.length; i += 1 ) {

                    if( values[ i ] === option.value ) {

                        return true;

                    }

                }

                return false;

            }

        }

        return returnFn;

    }() );

    return function selectValues(elem, values) {

        var 
            i,
            option;

        if( typeof elem !== "object" || typeof elem.nodeType === "undefined" )
            throw 'selectValues() expects a DOM Node as it\'s first parameter, ' + ( typeof elem ) + ' given.';

        if( typeof elem.options === "undefined" ) 
            throw 'selectValues() expects a <select> node with options as it\'s first parameter.';

        for( i = 0; i < elem.options.length; i += 1 ) {

            option = elem.options[ i ];

            option.selected = inArray( option, values );

        }

    }

}());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文