[英]Toggle state of textbox with javascript using a button
我的表格如下:
<form>
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock" onMouseDown="toggleInput()"></button>
</form>
和javascript代碼:
function toggleInput(){
if ($("#input").disabled){
$("#input").disabled = false;
}
else {
$("#input").disabled = true;
};
}
我基本上想要做的是檢查文本框處於什么狀態 (啟用/禁用),然后相應地切換狀態。 我不知道JavaScript部分是否甚至使用正確的語法來檢查文本框是否已禁用,但這是我能想到的。
提前致謝!
編輯:關於為什么我選擇使用onmousedown而不是onclick來通過按鈕執行事件的原因:
我選擇使用onmousedown而不是onclick,因為它具有onclick的功能,這使我正在構建的應用程序顯得不太笨拙:當您單擊按鈕時,然后按住鼠標將光標拖離按鈕按鈕,然后當光標位於網頁按鈕之外的區域時,將手指從鼠標按鈕上移開,該事件將不會執行。 因此,我選擇使用onmousedown來解決此問題。
要使用jQuery,請嘗試以下操作:
$("#input").prop("disabled", function(i, v) { return !v; });
您現有的代碼無效,因為DOM元素具有.disabled
屬性,但jQuery對象沒有。
我不確定為什么要使用onmousedown
而不是onclick
作為按鈕,但是無論哪種方式,如果您要使用jQuery,我建議刪除內聯事件屬性,以便將處理程序與jQuery綁定:
$("#lock").on("click", function() {
$("#input").prop("disabled", function(i, v) { return !v; });
});
(您需要將該代碼包含在正文末尾的腳本塊中或包含在文檔就緒處理程序中。)
演示: http : //jsfiddle.net/a7f8v/
您應該在事件處理程序中附加jQuery而不是onMouseDown事件。 語法如下所示:
<label for="input">Input:</label>
<input type="text" id="input" maxlength="3"></input>
<button type="button" id="lock"></button>
JavaScript:
$(document).ready(function() {
$("#lock").click(function() {
var input = $("#input");
input.prop('disabled',!input.is(':disabled'))
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.