2013-06-13 29 views
2

我有這樣的文本字段中輸入:jQuery的按下按鈕上的文本字段

<input id="address" type="text" value=""> 

,這個按鈕:

<input id="ricerca" type="button" class="enter" value="GO!"> 

和jQuery:

$("#ricerca").click(function(){ 
    var e = jQuery.Event('keypress'); 
    e.which = 13; // #13 = Enter key 
    $("#address").focus(); 
    $("#address").trigger(e); 
}); 

我想模擬通過點擊#ricerca按鈕,在「輸入」按鈕INSIDE #address字段中。按下按鈕時,光標必須位於#address字段內。

你能說我錯誤在哪裏嗎?

+0

你真的需要模擬這樣的說法?你能不能把這個工作抽象成一個函數並在兩個地方調用它? – NicoSantangelo

+0

我有一個Google地圖API 3的搜索框('input text'),帶有geolocator和一個Javascript屏幕鍵盤。當我在文本輸入上搜索時,按Enter鍵,我得到結果。所以我需要屏幕鍵盤發生同樣的事情。如果有一個更簡單的方法來模擬,那麼比我可以使用它! – Perocat

+0

'' – Igor

回答

13

定義的按鍵事件應該發生什麼#address。看看這個代碼。從文本框中按enter鍵,然後點擊按鈕,都會觸發按鍵事件。

演示 - http://jsbin.com/ocohev/1/edit

$(function() { 

     $('#address').keypress(function (event) { 
      if (event.which == 13) { 
       alert("enter pressed"); 
       //return false; only if needed 
      } 
     }); 

     $("#ricerca").click(function() { 
      var e = jQuery.Event('keypress'); 
      e.which = 13; // #13 = Enter key 
      $("#address").focus(); 
      $("#address").trigger(e); 
     }); 

    }); 
1

使用此jQuery代碼:

$("#id_of_textbox").keyup(function(event){ 
    if(event.keyCode == 13){ 
     $("#id_of_button").click(); 
    } 
}); 
相關問題