开发者

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

This question already has answers here: How do I check if an array includes a value in JavaScript? (60 answers) Closed 6 years ago.

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" ];


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
}


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 if an item is 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/


You could use -

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

Taken from this question - Best way to find if an item is in a JavaScript array?


well your array needs to be created like this:

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

or a json as follows:

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

with that in place now when you want to validate your form run it through all the inout element be using say $.each and then get the id of each of the input and get the vlaue of the same from the array that you have created or from the json compare the two values and see if it is correct.

code will be like:

$("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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜