Search code examples
javascriptasp.netrazor

select.options is undefined when trying to loop through ListBoxFor()


Im getting this error and i dont understand why. Please help. What Im trying to do is loop through all the options on a multiselectlist.

HTML/Razor

@Html.ListBoxFor(model => model.SelectedUsersIdsArray, new MultiSelectList(Model.Users, "ID", "NAME"), new { id = "Select", multiple = "multiple" })

JavaScript

var filterFuncionarios = [];
    @foreach (var f in Model.Funcionarios)
    {
        @:filterFuncionarios.push({ Id: "@f.ID"})
    }
    var selecionados = $('#usersSelectDropdown')[0].options;
    
    function filtraListDeFuncionarios() {
        for (var i = 0; i < this.selecionados.length; i++) {
            for (var k = 0; k < filterFuncionarios.length; i++) {
                if (selecionados[i].value == filterFuncionarios[k].Id) {
                    selecionados[i].selected = true;
                }
            }
        }
    }

This is the exact code im running.

Error Uncaught TypeError: selecionados[i] is undefined


Solution

  • You're already reading the options array here:

    var select = $('#Select')[0].options;
    

    Which you loop over:

    for (var i = 0; i < select.length; i++) {
    

    But then you try to read another options property on that same array:

    if (select.options[i].value == filterFuncionarios[k].Id) {
        select.options[i].selected = true;
    }
    

    Overall you've confused yourself with poor variable names. The initial variable is called "select" but it isn't a "select". It's an array of options. So call it that:

    var options = $('#Select')[0].options;
    

    Then looping over it is more intuitive:

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

    And accessing each option is clear:

    if (options[i].value == filterFuncionarios[k].Id) {
        options[i].selected = true;
    }