簡體   English   中英

如何在OnKeyPress事件之后獲取輸入表單元素的值?

[英]How do I get the value of a input form element after an OnKeyPress event?

如何在OnKeyPress事件之后獲取文本框的值? 例如,假設我有以下代碼:

<input type = "number" id = "foo" onKeyPress = "submit();"/>
<script type = "text/javascript">
function submit()
{
var textValue = document.getElementById("foo").value;
alert(textValue);
}
</script>

不幸的是,這是行不通的,因為在觸發OnKeyPress之后,變量textValue仍然落后一個字符。 我會使用OnKeyUp ,但遺憾的是,除非<input type = "text">在我的情況下不起作用,否則它無法在Android設備上使用。有人知道這樣做的方法嗎?

我建議改用input事件,它會在對輸入值進行任何更改后觸發(例如,通過鍵入字符,刪除,粘貼和拖放操作)。 這將適用於除IE <9以外的所有主要瀏覽器。

document.getElementById("foo").addEventListener("input", function() {
    alert("CHANGED!");
}, false);

嘗試以下代碼

<input type = "number" id = "foo" onKeyPress = "submit(this);"/>
    <script type = "text/javascript">
    function submit(e) {
      alert(e.value);
    }
    </script>

如果唯一的問題是Android設備,建議對其他所有人使用onkeyup。 然后,您可以檢測它是否為android(或輸入是否支持鍵盤輸入),並在必要時實施特定於Android的解決方案。

function submit(){
    function submitNow() {
        var textValue = document.getElementById("foo").value;
        alert(textValue);
    }   
    if(isAndroid) {
        setTimeout(submitNow, 10);
    }
    else {
        submitNow() ;
    }
}

var isAndroid = navigator.userAgent.toLowerCase().indexOf("android") > -1; 
var eventType = (isAndroid) ? "keyup" : "keypress" ;
document.getElementById("foo").addEventListener(EventType, submit);

然后,您可以刪除onKeyPress = "submit();" 從您的輸入。

如果不在Android上,則此代碼將使用keyup事件正常運行。 當客戶端在Android上時,它將等待1/100秒,這是足夠的時間來更新輸入,但時間太短而無法察覺。

通常,我會警告您不要長按按鍵,但是我不知道支持它們的Android鍵盤。

僅限Android解決方案:

function submit(){
    function submitNow() {
        var textValue = document.getElementById("foo").value;
        alert(textValue);
    }   
    setTimeout(submitNow, 10);
}

document.getElementById("foo").addEventListener("keyup", submit);

您甚至可以保留onKeyPress = "submit();" 如果您真的喜歡它。 只需刪除最后一行即可。

您是否嘗試過使用jQuery?

要將jQuery添加到您的頁面,只需將<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>在頁面頂部。

然后執行所需的操作,使用代碼

<script type="text/javascript">
  $("#my_field").keydown (function (e) {
      alert ($(this).val());
  });
</script>

其中#myField是您的字段的ID。

注意:您將不再需要輸入中的按鍵事件。

暫無
暫無

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

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