简体   繁体   中英

jquery inArray not found value

I'm trying to find selected value in array but what i tried so far not working:

 var array = [0, 74]; $('select').change(function() { var selected = $('select option:selected').val(); if ($.inArray(selected, array) != -1) { alert('found'); } else { alert('not found'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="0" selected="selected">----</option> <option value="59">ss</option> <option value="61">aa</option> <option value="62">zz</option> <option value="60">yy</option> <option value="74">xx</option> </select>

it works with $.each but i don't want use any loop my goal is get this with inArray . if selected value is 0 or 74 it should alert found but it not works.

Use indexOf() function for find in array.

Chanhe type selected to integer parseInt() (array is integers)

 var array = [0, 74]; $('select').change(function() { var selected = parseInt($('select option:selected').val(), 10); if(array.indexOf(selected)!=-1){ alert('found'); } else { alert('not found'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <select> <option value="0" selected="selected">----</option> <option value="59">ss</option> <option value="61">aa</option> <option value="62">zz</option> <option value="60">yy</option> <option value="74">xx</option> </select>

val returns a string and inArray does strict comparison

 var array = [0, 74]; $('select').change(function() { var selected = $('select option:selected').val(); // convert to a number if ($.inArray(+selected, array) != -1) { alert('found'); } else { alert('not found'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select> <option value="0" selected="selected">----</option> <option value="59">ss</option> <option value="61">aa</option> <option value="62">zz</option> <option value="60">yy</option> <option value="74">xx</option> </select>

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