如何使用Jquery或javascript检查输入的值是否存在

时间:2015-03-25 06:23:58

标签: javascript jquery

我有一个文本框和一个按钮,按钮上我写了下面的代码。问题是假设我首先输入文本框10而不是它的工作但当另一次我输入10时也打印值不在数组中。所以请帮我解决这个问题...

jQuery(document).ready(function()
{
 jQuery("#mybutton").live('click',function () 
 {
    var sel_fam_rel=jQuery("#my_textbox").val();
    var ids = [];
    code =sel_fam_rel;
    if($.inArray(code,ids) >= 0)
    {
      alert("Value is in array");
    }
    else
    {
      alert("Value is not in array");
      ids.push(code);
    }
  });
});

5 个答案:

答案 0 :(得分:2)

这一行:

if($.inArray(code,ids) >= 0)

应更改为:

if($.inArray(code,ids) != -1)

并将你的ids var置于点击之外。

试试下面的代码段。



var ids = [];
jQuery("button").on('click', function() {
  var sel_fam_rel = jQuery("#my_textbox").val();

  code = sel_fam_rel;
  if ($.inArray(code, ids) != -1) {
    alert("Value is in array");
  } else {
    alert("Value is not in array");
    ids.push(code);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='my_textbox'>
<button>check</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用下面的代码。将你的id带到click事件的一边。每次单击按钮ID复位时,根据您的代码。

var ids = [];  // declare as global variable
jQuery(document).ready(function()
{
  jQuery("#mybutton").live('click',function () 
  {
    var sel_fam_rel=jQuery("#my_textbox").val();
    code =sel_fam_rel;
    if($.inArray(code,ids) >= 0)
    {
     alert("Value is in array");
    }
   else
   {
     alert("Value is not in array");
     ids.push(code);
    }
 });
});

答案 2 :(得分:1)

创建数组var ids=[];全局外部按钮事件,因为无论何时单击按钮,它都会创建新的空数组。它会解决你的问题。

答案 3 :(得分:1)

需要进行一些更改:

var ids = []; // `ids` needs to be in the global scope to work as you want it, 
              //  or you could use a different method like localstorage 
jQuery(document).ready(function()
{
 jQuery("#mybutton").on('click',function () // use `on` not `live` which is deprecated
 {
    var sel_fam_rel=jQuery("#my_textbox").val();
    code =sel_fam_rel;
    if($.inArray(code,ids) != -1)  // inArray() returns -1 if the value is not in the array, you can use it the way you have it, IMO (purely subjective), using `!=-1` is preferable as it's more clear what the code in intend to do
    {
      alert("Value is in array");
    }
    else
    {
      alert("Value is not in array");
      ids.push(code);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_textbox" value="10"/><br>
<input type="button" id="mybutton" value="Click me"/>

答案 4 :(得分:-1)

我弄错了你的问题,使用indexOf

http://jsfiddle.net/go8o34fq/

<强>的jQuery -

var array=["A","B","C","D"];

$('button').click(function(){
    var code=$('input').val();
    if(array.indexOf(code)==-1)
    {
        array.push(code);
       console.log("if "+array)
    }
    else
    {
      console.log("else "+array)
    }
});

如果您的需求区分大小写,请使用 - code.toUpperCase()

相关问题