Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Selected Indices in Multi Select Using Javascript

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();
            }
        }
    }
like image 647
CatchingMonkey Avatar asked Nov 04 '22 10:11

CatchingMonkey


1 Answers

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");
        }
    }
}
like image 70
simshaun Avatar answered Nov 12 '22 17:11

simshaun