2017-06-02 76 views
1

一個字符串我有一個HTML輸入此代碼自動完成:如何檢查輸入具有在JavaScript

$("#myinput") 
    .bind("keydown", function(event) { 
     // don't navigate away from the field on tab when selecting an item 
     if (event.keyCode === $.ui.keyCode.TAB 
            && $(this).data("autocomplete").menu.active) { 
      event.preventDefault(); 
     } 
    }) 
    .autocomplete({ 
     minLength: 0, 
     source: function(request, response) { 
      var results = [], 
       selectionStart = this.element[0].selectionStart 
       term = extractLast(request.term.substring(0, selectionStart)); 

       if (term.length > 0) { 
        console.log(term); 
       if(/*input has string "where"*/) 
       results = $.ui.autocomplete.filter(table1, term); 
       else 
       results = $.ui.autocomplete.filter(table2, term); 
      } 
      response(results); 
     }, 
     focus: function() { 
      return false; // prevent value inserted on focus 
     }, 
     select: function(event, ui) { 
      var terms = split(this.value.substring(0, this.selectionStart)); 
      terms.pop(); // remove the current input 
      terms.push(ui.item.value);  // add the selected item 
      this.value = 
       $.trim(terms.join(" ") + this.value.substring(this.selectionStart)) + " "; 
      return false; 
     } 
    }); 

如果輸入有字符串我試圖做的是「地方」,在某個地方,那麼它將從table1加載自動完成,否則它將從table2加載。我怎樣才能檢查輸入是否有該字符串?提前致謝。

+0

,你可以使用'檢查typeof' https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/typeof –

+0

你的意思是在你的輸入框中的值? –

+0

@MohideenibnMohammed是的。 – jason

回答

1

您應該使用includes方法。

var inputValue=$("#myinput").val(); 
if(inputValue.toLowerCase().includes("where")){ 
    //rest of code 
} 

另一種方法是使用indexOf方法。

if(inputValue.indexOf("where")!==-1){ 
    //rest of code 
} 

如果你想這樣做使用regex這achievment,您可以使用search方法。

if(inputValue.search(/where/i)!==-1){ 
    //rest of code 
} 

inputValue="awherea"; 
 
console.log(inputValue.search(/where/))

+1

str.search也適用 – Rahul

+0

我認爲'indexOf'更好,因爲IE不支持'includes' –

+1

也可以使用'match' –

0

如果你想最強的瀏覽器支持,使用String#indexOf

if(this.value.indexOf('where') > -1) { 
    //doSomething 
} 
0

你可以得到你的文本價值和使用的indexOf找到它。

my_inp = $("#myinput").val(); 
if (my_inp.indexOf('where') > -1) { 
    console.log('yes'); 
} 
0

嘗試用string#match方法使用ternary operator的返回true或false

,也有一些更多的方法

  1. string.indexOf()
  2. string.includes()

的jQuery你可以使用contains()方法

console.log($('p').is(':contains("hi")')) 
 
console.log($('p').is(':contains("22")')) // not contains
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>hello hi</p>