jQuery Tutorial
In this blog, let us know how can we check whether particular element exists in an array or not in jQuery.
inArray method is used to renturn a value's index in an array or -1 if the value is not found in the array.
Let us knnow the syntax to use inArray method,
$.inArray(element, arrayVariable);
We are going to see the example jQuery code to find a value found in an array or not,
<!DOCTYPE html>l <html>l <head>l <title>lPage Title</title>l <script src="https://code.jquery.com/jquery-1.9.1.min.js">l</script>l <script type="text/javascript">l $(function () { var arrStr = ["Testing1", "Testing2", "Testing3", "Testing4"]; var str = "Testing1"; checkString(str, arrStr); var str = "Testing6"; checkString(str, arrStr); }); function checkString(str, arrStr) { if ($.inArray(str, arrStr) != -1) { $('#result').append("<p>lstr is found in array 'arrStr'</p>l"); } else { $('#result').append("<p>lstr is not found in array 'arrStr'</p>l"); } } </script>l </head>l <body>l <div id="result">l</div>l </body>l </html>l
Output:
We can change the above jquery code to return a value's index position in array.
<!DOCTYPE html>l <html>l <head>l <title>lPage Title</title>l <script src="https://code.jquery.com/jquery-1.9.1.min.js">l</script>l <script type="text/javascript">l $(function () { var arrStr = ["Testing1", "Testing2", "Testing3", "Testing4"]; var str = "Testing3"; checkString(str, arrStr); var str = "Testing6"; checkString(str, arrStr); }); function checkString(str, arrStr) { var index = $.inArray(str, arrStr); if (index != -1) { $('#result').append("<p>lstr is found in array 'arrStr' at: index position "+index+"</p>l"); } else { $('#result').append("<p>lstr is not found in array 'arrStr': index position " + index +"</p>l"); } } </script>l </head>l <body>l <div id="result">l</div>l </body>l </html>l
Output:
Linux Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page