With the help of inArray function you can check value exists in array or not.
$.inArray function return the index of element. If element not exist in array it will return -1. So, we can check it very simply weather a value exist in array or not. Please see given example.
$.inArray function return the index of element. If element not exist in array it will return -1. So, we can check it very simply weather a value exist in array or not. Please see given example.
CODE
<!DOCTYPE html> <html> <head> <title>jQuery With Example</title> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $('.btnClick').click(function () { var country = []; country.push('Japan'); country.push('England'); country.push('India'); alert($.inArray('India', country)); alert($.inArray('Pakistan', country)); if ($.inArray('Pakistan', country) < 0) { alert('Pakistan not found'); } else { alert('Pakistan found'); } }); }); </script> </head> <body> <div> <input type="button" class="btnClick" value="Click" /> </div> </body> </html>
DISPLAY
The return value for $.inArray if the condition is false is '-1'. So the Condition should be
ReplyDeleteif ($.inArray('Pakistan', country) <= 0)
Thanks to read this blog.
DeleteBut if ($.inArray('Pakistan', country) <= 0) will not work if this country at 0 position. Because array index start from 0.
So, condition must be if ($.inArray('Pakistan', country) < 0)
or if ($.inArray('Pakistan', country) == -1)
!!!
ReplyDelete