JS jQuery的 - 检查是否值是数组 [英] JS jQuery - check if value is in array

查看:138
本文介绍了JS jQuery的 - 检查是否值是数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更多的PHP的人,不是JS的 - 我想我的问题更多的是语法问题。

I am more of a PHP person, not JS - and I think my problem is more a syntax problem ..

我有一个小jQuery来验证,并检查输入值。

I have a small jQuery to "validate" and check input value .

它的工作原理确定为单个的词,但我需要的数组。

It works ok for single words, but I need array.

我使用的是 inArray()的jQuery。

I am using the inArray() of jQuery .

var ar = ["value1", "value2", "value3", "value4"]; // ETC...

        jQuery(document).ready(function() {

            jQuery("form#searchreport").submit(function() {
            if (jQuery.inArray(jQuery("input:first"), ar)){ 
                      //if (jQuery("input:first").val() == "value11") { // works for single words
            jQuery("#divResult").html("<span>VALUE FOUND</span>").show();
            jQuery("#contentresults").delay(800).show("slow");
                return false;
              }

        // SINGLE VALUE SPECIAL CASE / Value not allowed 
               if (jQuery("input:first").val() == "word10") {

                jQuery("#divResult").html("YOU CHEAT !").show();
                jQuery("#contentresults").delay(800).show("slow");

                return false;
              }

        // Value not Valid

              jQuery("#divResult").text("Not valid!").show().fadeOut(1000);

              return false;
            });

        });

现在 - 这如果(jQuery.inArray(jQuery的(输入:第一),AR))不正确的工作。每天我把价值将验证为OK。 (即使是空的)

now - this if (jQuery.inArray(jQuery("input:first"), ar)) is not working right .. every value that I put will be validated as OK . (even empty)

我需要从数组(AR)验证只值。

I need to validate only values from the array (ar) .

我也试过如果(jQuery.inArray(jQuery的(输入:第一),AR)== 1)// 1,0,-1想尽一切

我在做什么错了?

奖金的问题:如何才能不办在数组中的jQuery?
!<:I SW somehre,它不会工作,并且需要使用像这样 - (PHP 如果(in_array('1',$ A))相当于code> !!〜

Bonus question : how to do NOT in array in jQuery ?? (the equivalent of PHP if (!in_array('1', $a)) - I sw somehre that it will not work , and need to use something like this : !!~

推荐答案

您要比较一个jQuery对象(的jQuery(输入:第一'))为字符串(该数组的元素)。结果,
改变code,以便将输入的值(至极是一个字符串)比较数组元素:

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

inArray 方法的返回值 1 如果元素没有在数组中,从而为你的奖金的答案如何确定一个元素的不可以在一个阵列,使用:

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

这篇关于JS jQuery的 - 检查是否值是数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆