i will show you how you can do a search and find for a var value with in array in javascript code [835], Last Updated: Sat May 18, 2024
wallpaperama
Sun Oct 23, 2011
0 Comments
518 Visits
today i was writing some javascript and i wanted to know how i can search for a particular word or value within an array.
lets say for example i have four elements in an array, for each element, it contains the value of a color
i want to have a form where the user enters the color they want to search for and if there is a match, it shows a message, also if there is no match, and it shows a message also.
so this is how i did it, here's the code:
<script type="text/javascript" language="javascript"> function Search(id){ var Counts = Colors.length; var Mycolor = document.getElementById(id).value for (i=0;i<Counts;i++){
if(Colors[i] == Mycolor){ alert('You Entered: ' + Mycolor +' and I found ' + Colors[i] + ' on element #' + i); return; }
} alert('I didnt find ' + Mycolor + ' In the Array'); } var Colors = new Array(); Colors[0] = 'red'; Colors[1] = 'blue'; Colors[2] = 'white'; Colors[3] = 'green'; </script> <br /> Enter Color to find: <input type="text" id="MyColor" /><input type="button" value="Search" onclick="Search('MyColor');" /> <div style="text-align:center;padding:15px;">By <a href="http://www.wallpaperama.com">Wallpaperama.com</a><!-- please dont remove our link--></div>