How to check whether element is in Array using jQuery ?

jQuery $.inArray

inArray function is used to return a value's index in an array if value is available in the array, otherwise -1 if value is not in the array.

$.inArray(value, array)

Returns the value index if value is in array, otherwise -1.

jQuery Example - To check whether input is in array or not

There are cities in the array AB, BC and CD. this jQuery code is used to check whether city is provided by the user is available in the array or not.

      <title>jQuery inArray function</title>

 <script src=""></script>	
      <script type = "text/javascript">
        function validate_city() {
	var valid_cities = ["AB", "BC", "CD"];
        if($.inArray($("#txtCity").val(), valid_cities) !== -1) {
	  alert("Valid city!");
        } else {
  	  alert("Invalid city!");

<p>City: <input type="text" id="txtCity" value="" /></p>
<input type="button" value="Verify City" onclick="validate_city();"/>

When providing the city which is available in the array:

found in array output

When providing the city which is not in the array:

not found in array output

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter