我需要啓用文本框,當用戶開始打印它時結束禁用按鈕時,文本框是空的。如何清除文本框時禁用按鈕?
這裏是我的文本框和按鈕:
<button id="btnSaveLayer" class="ui-btn ui-icon-plus ui-btn-icon-left ui-btn-b" onclick="SaveNewLayer()" disabled>save</button>
<input type="text" id="newLayerName" placeholder="name" value="" />
這裏是我使用的代碼:
function setElementsDisabled() {
$('#newLayerName').keyup(function() {
if ($(this).val().length != 0)
$('#btnSaveLayer').attr('disabled', false);
else
$('#btnSaveLayer').attr('disabled', true);
})
}
從功能上面可以看到,當用戶開始輸入文字文本框啓用並且當用戶從文本框中刪除按鈕被禁用。
它工作完美!
但是,當我清除按鈕編程方式使用此jQuery代碼:
$("#newLayerName").val('');
從文本框中的文本被刪除,但,未禁用按鈕。
任何想法如何更改我的功能setElementsDisabled
,以便當文本框爲空時,按鈕被禁用?
也許'<'而不是'!='而且你可以做的也是當你觸發空按鈕的時候也在同一個調用中設置'disabled true'。這樣,當某人清除輸入時,該按鈕會自動阻止。 – hansTheFranz
查看答案我給出如下 –
https://learn.jquery.com/using-jquery-core/faq/how-do-i-disable-enable-a-form-element/ – epascarello