Search code examples
javascriptindexof

JavaScript String indexOf() selects also 1&3 instead of only 13


I have this indexOf(), the issue I have is that when norms[] has an dataset like 2,13 that options that are set as selected in norm_id['+nr+'][] are not only the values 2 and 13 but also the values 1 and 3

var element = document.getElementById('norm_id['+nr+'][]');
var values = norms[];
for (var i = 0; i < element.options.length; i++) {
   element.options[i].selected = values.indexOf(element.options[i].value) >= 0;
}

Any suggestions how to solve this?


Solution

  • I have solved the issue with the code below.

    var element = document.getElementById('calc_norm_id['+nr+'][]');
    var values = norms;
    var values_split = values.split(',');
    
    for (var i = 0; i < element.options.length; i++)
    {
       for(var j = 0; j < values_split.length; j++)
       {
           if(element.options[i].value == values_split[j])
           {
               element.options[i].selected = element.options[i].value;
           }
       }
    }
    

    @Andreas thx for the tip