I’ve got some code that looks like this. The values of select#member_id get added dynamically by PHP. I’m trying to determine whether the user selects a res or com option from the list, which will determine whether I dynamically add in a second dropdown. With the code as is, I consistently get -1 alerted by the script. The console.log call prints out: [1, 3] [2].
<script>
var res_members = new Array();
var com_members = new Array();
</script>
<p><select name="member_id" id="member_id">
<option value=""></option>
<option value="1">Alice (res)</option><script>res_members.push(1);</script>
<option value="2">Bob (com)</option><script>com_members.push(2);</script>
<option value="3">Carl (res)</option><script>res_members.push(3);</script>
</select></p>
<script>
console.log(res_members, com_members);
$(function(){
$('#member_id').change(function(){
alert($.inArray($('#member_id').val(), res_members));
alert($.inArray($('#member_id').val(), com_members));
});
});
</script>
Why don’t you go with something simpler and more convenient like this:
See it in action.
Update: Why your current code doesn’t work
It’s because you are pushing integers into the array (with
push), while you are searching for strings with$.inArray. Changing either of these would make the existing code work.So one solution would be to push in strings:
And another would be to look for integers:
Evidently
$.inArraycompares haystack elements with the needle using operator===.