Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: check input value against values in an array [duplicate]

I'm attempting to check the values entered by a user into an input text field. Once they enter the value and click submit, if the value they enter matches a value in an array, I'm attempting to produce one result, if not in the array, another result.

Basically have a simple form like so:

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

When click "#submit", if value in the "#couponcode" input field equals the value in an array, add a class of "success" to a div with an id of "success_show" otherwise a simple alert like "your coupon code is wrong" would be displayed.

I'll have a hidden div and upon success, add a class of "success" to the div.

The array will change periodically and will have different quantities at different times. Something simple like so:

var arr = [ "CA238", "Pete", 8, "John" ];
like image 696
flinx777 Avatar asked Dec 09 '22 06:12

flinx777


1 Answers

You can use jquery...

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

EDIT If you don't use jQuery then you can use indexOf on the array

if(array.indexOf(value) < 0){ // doesn't exist
    // do something
}
else { // does exist
    // do something else
}
like image 187
gislikonrad Avatar answered Dec 15 '22 00:12

gislikonrad