jQuery Find Value In Array Examples
Talking about arrays in jQuery, it can be really helpful to know if a value exists in an array or not. That said, in this article, I am going to share examples on how to find if a specific value exists in an array or not using jQuery. Try the demo to see how it works in real time.
How To Find If A Value Exists In Array Or Not Using jQuery
Let’s assume that we have an array of fruits. Now we would like to search if this array contains a fruit of our choice. Let’s see how this can be done.
Example: Check if a value exists in an array when a button is clicked
<input type="submit" name="sbt_check" id="sbt_check" value="Check if 'mango' exists in array"> <input type="submit" name="sbt_check_straw" id="sbt_check_straw" value="Check if 'strawberry' exists in array"> <script type="text/javascript"> $(document).ready(function(){ var fruits_array = new Array('grapes', 'apple', 'mango'); $('#sbt_check').on("click", function(e){ var search_for = 'mango'; if($.inArray(search_for, fruits_array) > -1) { alert("Mango exists in the array"); } else { alert("Mange does not exist in array"); } e.preventDefault(); }); $('#sbt_check_straw').on("click", function(e){ var search_for = 'strawberry'; if($.inArray(search_for, fruits_array) > -1) { alert("Strawberry exists in the array"); } else { alert("Strawberry does not exist in array"); } e.preventDefault(); }); }); </script>
In the above example, when the first button is clicked, the value ‘mango’ is searched for and the result is displayed. When the second button is clicked, the value ‘strawberry’ is searched for and the result is displayed.
Simple, isn’t it?
Do you know of any other ways to find value in array of objects using jQuery? Feel free to suggest by commenting below.