2017-06-18 71 views
0

這是按鈕創建的按鈕,當用戶單擊搜索選項卡時,該按鈕具有可進入頁面的功能,但我需要它在用戶壓力機也進入。如何在用戶按下輸入時使搜索工作

這是搜索欄和按鈕

<input type="text" method="get" class="form-control" id="search" placeholder="Search" value=""> 
<button type="button" id="go" class="btn btn-default" onclick="sendToPage();">Search</button> 

這是函數

function sendToPage(){ 
    var input = document.getElementById("search").value; 

    //Check to see if the user has entered apple/iphone; 
    if (input === "apple"){ 
     //location.href="apple.html";      
     location.replace("apple.html"); 
     return false; 
    } 
    else if (input === "iphone"){ 
     location.replace("apple.html"); 
     return false; 
    } 
} 
+0

你的按鈕點擊代碼在哪裏?或者什麼是按鈕名稱? –

回答

0

您可以添加keyup,檢查其event.keyCode。如果鍵碼是13,則表示用戶在輸入文本上單擊了輸入。

事情是這樣的:

document.getElementById("search") 
    .addEventListener("keyup", function(event) { 
    event.preventDefault(); 
    if (event.keyCode == 13) { 
     if (input === "apple")    
      location.replace("apple.html"); 
     else if (input === "iphone") 
      location.replace("apple.html"); 
    } 
    return false; 
}); 

或使用功能sendToPage()

document.getElementById("search") 
    .addEventListener("keyup", function(event) { 
    event.preventDefault(); 
    sendToPage(); 
    return false; 
}); 
+0

嘗試使用,但然後表單提交每次我按下一個鍵時,當用戶開始鍵入他們尋找它觸發事件和搜索功能不運行 –

-1
This is the button 

<!-This is the button --> 
<div id="search-bar"> 
<div class="form-group"> 
    <input type="text" method="get" class="form-control" id="search" placeholder="Search" value=""> 
    <button type="button" id="go" class="btn btn-default" onclick="sendToPage();" onChange="aliasonclick">Search</button> 
</div> 
</div> 
0

看來你輸入字段的ID是 '搜索',所以你可以試試這個: 請注意,輸入的鍵碼是13.因此我們可以將輸入的碼與13進行比較。如果它的真實,那麼進行搜索。

$('#search').keydown(function(event) { 
    if (event.keyCode == 13) { 
     var input = $(this).val(); 
     if (input === "apple"){ 
      //location.href="apple.html";      
       location.replace("apple.html"); 
       return false; 
     } 
     else if (input === "iphone"){ 
       location.replace("apple.html"); 
       return false; 
     } 
     return false; 
    } 
    }); 

}); 
+0

謝謝安庫什,這是有道理的。我會嘗試這個例子。 –

+0

Iv'e嘗試過所有這些示例,但它們都不起作用:( –

1

在輸入周圍放置一個表格應該會給你你要找的結果。然後,只需在調用sendToPage()的窗體中添加一個「onsubmit」;功能。

+0

我試過,然後onclick函數不起作用 –

+0

@JadePage按鈕的onclick函數不適用於表單中的onsubmit? – SirPizzaRolls

+0

沒有任何作用當我使用表單並更改onClick並提交 –

相關問題