Online Snippets Library

Check value exist in array using jQuery

To check value exist in array or not we will use jQuery.inArray method. jQuery.inArray method return the index of element. If searched element not found in array it will return -1.

Syntax

jQuery.inArray( value, array [, fromIndex ] )

Example

HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"> </script>
<title>Check value exist in array using jQuery</title>
</head>
<body>
<P>Array : ["Mycar", "Volvo", "BMW"]</P>
<input type="text" id="inputVal" value="">
<button id="check">Check value exist or not</button>
</body>
</html>
Javascript
$(document).ready(function(){
$("#check").click(function(){
var arr = ["Mycar", "Volvo", "BMW"];
var inputVal = $("#inputVal").val();
if(jQuery.inArray(inputVal,arr )<0)
{
alert('Value not found');
} 
else
{
alert('Value found');
}
});
});