1

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.

2
  • 1
    change the array to var array = ["0", "74"]; Commented Oct 29, 2017 at 18:49
  • api.jquery.com/jQuery.inArray Comparison is "Strict", either convert "array" to type String or type cast "selected" to INT. Commented Oct 29, 2017 at 18:55

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.