简体   繁体   English

使用jQuery $ .inArray验证JSON中是否存在值

[英]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. 我正在尝试使用jQuery的$ .inArray方法来验证JSON数组中是否存在特定值。

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. 当前,JS脚本上方有一个表单字段,用于接收用户输入,并且在输入或单击“提交”后,应根据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!" 如您所见,其想法是,如果用户输入的值与JSON数组中的值匹配,则它应返回0或更高值并触发“您知道了!” 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. 我已经使用console.log查看zipcode变量是否被删除或未保存,但这似乎不是问题。

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... 但是,我没有使用$.InArray()因为据我所知它在这里不适用...

$('#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/ 演示: 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. 您需要检查数组中每个objectZIPCode值。

One handy utilty function for this in jQuery is $.grep() which will filter an array based on conditions and return a new array. jQuery中方便使用的实用函数是$.grep() ,它将根据条件过滤数组并返回一个新数组。 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 $ .grep()API文档

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"}] var theCodes = [{“ ZIPCode”:20001,“ Market”:“ Washington DC”},{“ ZIPCode”:20004,“ Market”:“ Washington DC”},{“ ZIPCode”:20005,“ Market”:“华盛顿特区“},{”邮政编码“:20006,”市场“:”华盛顿特区“},{”邮政编码“:20007,”市场“:”华盛顿特区“},{”邮政编码“:20008,”市场“: “华盛顿特区”},{“邮政编码”:20009,“市场”:“华盛顿特区”},{“邮政编码”:20012,“市场”:“华盛顿特区”}]

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

as you did 'var zipcode = $('form').find('input[name="zipcode"]').val();' 就像您所做的那样'var zipcode = $('form')。find('input [name =“ zipcode”]')。val();' to get the input, but the type of value is string, so $.inArray always output -1 获取输入,但是值的类型是字符串,因此$ .inArray始终输出-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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