简体   繁体   中英

Using jQuery $.inArray to validate whether or not value exists in JSON

all.

I am trying to validate whether or not a particular value exists in a JSON array using jQuery's $.inArray method.

Presently there is a form field above the JS script that receives user input and, on enter or click of 'submit,' should validate that input against the JSON. The code is as follows:

<form>
      <label for="zipcode">Enter your zipcode</label>
      <input type="text" id="zipcode" name="zipcode"> </br>
      <input id="user_info" type="submit">
</form>
<p></p>

...

$('document').ready(function(){
 $('#user_info').on("click", function(e){
  e.preventDefault();
  var zipcode = $('form').find('input[name="zipcode"]').val();
  if($.inArray(zipcode, theCodes)!==-1) {
    $("p").text("You got it!");
  } else {
    $("p").text("You don't got it!");
  }
 }); //closes click handler
}); //closes document.ready

var theCodes = [{"ZIPCode":20001,"Market":"Washington DC"},
                          {"ZIPCode":20004,"Market":"Washington DC"},
                          {"ZIPCode":20005,"Market":"Washington DC"},
                          {"ZIPCode":20006,"Market":"Washington DC"},
                          {"ZIPCode":20007,"Market":"Washington DC"},
                          {"ZIPCode":20008,"Market":"Washington DC"},
                          {"ZIPCode":20009,"Market":"Washington DC"},
                          {"ZIPCode":20012,"Market":"Washington DC"}]

As you can see, the idea is that if the user inputted value matches with a value in the JSON array it should return 0 or above and trigger "You got it!" appended to the

element. However, at present, it triggers "You don't got it!"

I've used console.log to see if the zipcode variable is being dropped or not saved, but that doesn't seem to be the problem.

Any ideas how to proceed?

It's late at night and I know this code isn't good; but it does what you ask! However, I did not use $.InArray() since it isn't applicable here as I could tell...

$('#user_info').on('click', function(){
    var IsInArr = function(needle, haystack){
        for (var i = 0; i < haystack.length; i++) {
            if (haystack[i].ZIPCode == needle) {
                return true;
            }
        }
        return false;
    };
    if (IsInArr($('#zipcode').val(), theCodes)) {
        $('p').text('You got it');
    } else {
        $('p').text('You don\'t got it');
    }
});

DEMO: http://jsfiddle.net/j476sruj/

You are trying to compare a string value to an array of objects. This can't work simply because they aren't even the same type, let alone match in value.

You need to check the ZIPCode value of each object in the array.

One handy utilty function for this in jQuery is $.grep() which will filter an array based on conditions and return a new array. If the new filtered array has no length there is no match, otherwise there is.

var zipcode= parseInt( $('#zipcode').val(),10) ;
 /* should validate string length and valid number before wasting time in folowing loop*/
var validZip=$.grep(theCodes, function(item){
            return item.ZIPCode == zipcode;
     }).length; /* use length of array as truth test */

 $("p").text( validZip ? "Valid Zip" :  'Ooops try again');

$.grep() API Docs

var theCodes = [{"ZIPCode":20001,"Market":"Washington DC"}, {"ZIPCode":20004,"Market":"Washington DC"}, {"ZIPCode":20005,"Market":"Washington DC"}, {"ZIPCode":20006,"Market":"Washington DC"}, {"ZIPCode":20007,"Market":"Washington DC"}, {"ZIPCode":20008,"Market":"Washington DC"}, {"ZIPCode":20009,"Market":"Washington DC"}, {"ZIPCode":20012,"Market":"Washington DC"}]

    console.log($.inArray('{"ZIPCode":20001,"Market":"Washington DC"}', theCodes));
    // output -1

as you did 'var zipcode = $('form').find('input[name="zipcode"]').val();' to get the input, but the type of value is string, so $.inArray always output -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM