当我对字段使用 jQuery 的 keyup
事件时,我想禁用所有字段,除非我正在访问的字段,而且,如果我的字段为空,则所有表单字段都必须为已启用。
这是 html 代码:
<form id="myform">
<div class="form-group col-xs-4 col-md-4">
<label for="customernumber" class="control-label">Customer Number</label>
<input type="number" class="form-control" id="customer-number" />
</div>
<div class="form-group col-xs-5 col-md-5">
<label for="surname" class="control-label">Surname</label>
<input type="text" class="form-control" id="surname" />
</div>
<div class="form-group col-xs-2 col-md-2">
<label for="datebirth" class="control-label">Date of Birth</label>
<div class='input-group date' id="datetimepicker1">
<input type='text' class="form-control" id="date-birth" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</form>
这是js代码:
$("#customer-number").keyup(function() {
$("#myform :input").prop("disabled", true);
})
怎么能做到呢?
谢谢
最佳答案
如果您想否定当前具有焦点的 input
元素,您可以使用选择器 $("#myform :input:not(:focus)")
或 $("#myform :input").not(this)
。
此外,如果您还想根据当前 input
元素是否有值来禁用其他字段,请根据输入的长度设置 disabled
属性当前元素的值:
$("#customer-number").on('input', function() {
$("#myform :input:not(:focus)").prop("disabled", this.value.length);
});
我还将 keyup
事件更改为 input
事件,以便每当值更改时(而不是每当按键按下时)都会触发该事件。
关于javascript - 如何禁用除选定字段之外的所有表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34317567/