JQuery: check input value for values ​​in array

I am trying to validate user-entered values ​​in an input text box. When they enter a value and click Submit, if the value entered matches the value in the array, I am trying to create one result, if not in the array, another result.

Basically, there is a simple form:

<form id="checkinput" action="#"> <input type="text" value="" id="couponcode" name="coupon code name"/> <input type="button" id="submit" value="Submit"/> </form> 

When you press "#submit", if the value in the input field "#couponcode" is equal to the value in the array, add the class "success" in the div with the identifier "success_show", otherwise a simple warning, for example, your coupon code is incorrect, will be displayed.

I will have a hidden div and after success add the class "success" to the div.

The array will periodically change and will have different values ​​at different times. Something simple:

 var arr = [ "CA238", "Pete", 8, "John" ]; 
+4
source share
4 answers

You can use jquery ...

 $.inArray(value, array) // returns -1 if value doesn't exist, otherwise returns index 

EDIT If you are not using jQuery, you can use indexOf for the array

 if(array.indexOf(value) < 0){ // doesn't exist // do something } else { // does exist // do something else } 
+10
source
 function include(arr, obj) { for(var i=0; i<arr.length; i++) { if (arr[i] === obj) return true; } } var arr = [ "CA238", "Pete", 8, "John" ]; $("#submit").click(function(e){ e.preventDefault(); var val=$("#couponcode").val(); if(include(arr, val)) alert("success"); }); 

http://jsfiddle.net/kCYkx/5/

hel taken from Best way to find an element in a JavaScript array?

OR

use inArray

 $("#submit").click(function(e){ e.preventDefault(); var val=$("#couponcode").val(); if($.inArray(arr,val)) alert("success"); }); 

http://jsfiddle.net/kCYkx/6/

+3
source

You can use -

 function include(arr,obj) { return (arr.indexOf(obj) != -1); } 

Taken from this question - Best way to find an element in a JavaScript array?

0
source

Well, your array should be created as follows:

 var a=[]; a["couponcode"]="CA238"; a["name"]="peter"; 

or json as follows:

 var a={ couponCode:"CA238", name: "peter"} 

so that now that you want to validate your form, run it through the entire inout element using say $.each , and then get the identifier of each of the input data and get the value of the same from the array you created or from json Compare the two values ​​and see if they are correct.

The code will look like this:

 $("input").each( function() { var id=$(this).attr("id"); if(a[id]) // for json a.hasOwnProperty(id) { if($(this).val()!==a[id]) { // do the necessary } } }); 
0
source

All Articles