簡體   English   中英

如何在JavaScript中的文本框的按鍵事件上啟用或禁用按鈕

[英]how to enable or disable a button on keypress event of a textbox in javascript

我創建了一個TextBox:-

TextBox ID="TxtUname" onKeyPress="ENABLE_BTN()"

現在我寫了一個函數:-

script type="text/javascript"

window.onload = function() { 
        document.getElementById('SSAccept').disabled = true; 
}; 
function ENABLE_BTN() {
     var EN=document.getElementById('TxtUname').value;
     if(EN=='') {
         document.getElementById('SSAccept').disabled=true;
     } else {
         document.getElementById('SSAccept').disabled=false;
     }
}
</script>

但是仍然無法在按下文本框中的任何鍵時啟用禁用的按鈕。 誰能告訴我我做錯了嗎? 提前致謝

開發人員

onkeypress不適用於所有瀏覽器-> http://www.quirksmode.org/js/keys.html

應該使用onkeyup / onkeydown >

工作示例: http : //jsfiddle.net/KCBzk/

HTML:

<input id="TxtUname" value="" onkeydown="ENABLE_BTN()"/><br>
<button id="SSAccept">Some test</button>

Javascript:

window.onload = function() {
    document.getElementById('SSAccept').disabled = true; 
}
function ENABLE_BTN() {
     var EN=document.getElementById('TxtUname').value;
     if(EN=='') {
         document.getElementById('SSAccept').disabled=true;
     } else {
         document.getElementById('SSAccept').disabled=false;
     }
}

問題是您需要一個事件來調用該函數。 您應該監視文本框的更改,並在值更改時調用該函數。 就像使用jQuery

$("#TxtUname").keydown(function(e) { 
    if($("#TxtUname").val == '') {
        //..disable button..
    } else {
        //..enable button
    }
});

暫無
暫無

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

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