2016-02-25 66 views
1

我需要檢測第一個按下後的第二個輸入。 案例:我有一個輸入表單,第一個輸入是選擇一個城市,第二個輸入是觸發提交。有沒有辦法做到這一點?如何檢測第二個輸入是在觸發鍵盤上觸發的?

$("#this_is_the_input").keyup(function(e) { 
    if (e.keyCode == 13) { 
     This is the first enter to select the city. 
     How do I detect the second enter to submit? 
    } 
}); 
+0

你能澄清第二進入?如果他們擊中進入,離開球場,然後返回並擊中輸入,這是否也被認爲是第二次輸入,或者這將是一個新的首次輸入? – Taplar

+0

您可以看到城市字段是否有價值。如果它確實提交了表格。 'if(e.keyCode == 13 &&!{{input class name}}。val())'和else if(e.keyCode == 13 && {{input class name}}。val())' – spasticninja

+0

您選擇的城市輸入JS代碼應該防止事件冒泡提交觸發器。你在使用什麼城市自動完成/鍵入? – CrnaStena

回答

0

這樣的事情應該適合你。 clicks變量跟蹤發生了多少keyup事件。希望你有正確的keyCode。如果它的第二個,那麼它調用第二個警報。告訴我,如果這不是你需要的。

var clicks=0; 
$("#this_is_the_input").keyup(function(e) { 
     console.log("clicks: "+clicks); 
    if(e.keyCode == 13) 
      clicks++; 
    if (e.keyCode == 13 && clicks == 1) { 
     console.log("first click"); 

    } 
    else if(e.keyCode == 13 && clicks == 2){ 
    console.log("second click"); 
    } 
}); 
+0

該代碼將永遠不會顯示「第二次點擊」,因爲你是'++點擊'總是做奇數。在if語句之前移動++點擊,參見[jsFiddle](https://jsfiddle.net/o9y9v2dh/)。 – CrnaStena

+0

就我個人而言,我可能會嘗試使用元素上的數據元素,所以它更加獨立。 – Taplar

+0

謝謝@CrnaStena – pritesh

0

試試這個:

count = 0 
$("#this_is_the_input").keyup(function(e) { 
    if (e.keyCode == 13) { 
     if(count == 0) 
     { 
      //This is the first enter to select the city. 
     }else 
     { 
      //This is the second enter to submit. 
     } 
    count++; 
    } 
});