简体   繁体   中英

search for values in select box using javascript/jQuery

I am trying to search the options within a HTML select to find which options have values matching any element in an array

For example, I have an array of integer values like so:

var arrTaken = [641, 640];

and I have a select element like so:

<select id="Substance3" name="Substance_3">
<option value="640">A</option>
<option value="641">B</option>
<option value="642">C</option>
<option value="643">D</option>
<option value="644">E</option>
</select>

Then I loop through the options on the select in an attempt to find any element value matching:

$('#Substance3 > option').each(function(index, element)
{
    console.log('current element value is: ' + element.value);
    var index = arrTaken.indexOf(element.value);
    console.log('element is at index: ' + index);
});

The problem is that the index is returned as -1, meaning the value was not found in the array. However, trying with

var index = arrTaken.indexOf(640);

works

What am I doing wrong here?

Convert the value to a number first:

 var index = arrTaken.indexOf(+element.value);
 //                           ^ unary plus

.indexOf uses strict equality comparison (same as === ). element.value returns a string, while your array contains numbers.

DEMO

将数组声明为此

var arrTaken = ['641', '640'];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM