簡體   English   中英

如何使用Jquery或javascript檢查輸入的值是否存在

[英]How to check entered value is exist or not using Jquery or javascript

我有一個文本框和一個按鈕,在按鈕上我寫了下面的代碼。 問題是假設首先我在文本框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); } }); }); 

這行:

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

應該更改為:

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

並將您的ID變量放在點擊之外。

試試下面的代碼片段。

 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> 

使用下面的代碼。 將您的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);
    }
 });
});

創建數組var ids=[]; 全局外部按鈕事件,就像您單擊按鈕時一樣,它正在創建新的空數組。 它將解決您的問題。

需要進行一些更改:

 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"/> 

我擺弄了你的問題,使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM