如何使用jQuery单击禁用/启用输入字段

如何使用jQuery正确启用/禁用点击输入字段?

我正在尝试:

$("#FullName").removeAttr('disabled'); 

从此输入字段中删除disabled="disabled"

  

但是如何通过单击另一个按钮再次添加它或如何在单击时禁用输入字段?

对于jQuery版本1.6+使用prop

 $('#elementId').click(function(){ $('#FullName').prop('disabled', true\false); }); 

对于旧版本的jQuery,请使用attr

 $('#elementId').click(function(){ $('#FullName').attr('disabled', 'disabled'\''); }); 
 $("#FullName").prop('disabled', true); 

会做。

但是在禁用它之后请记住(通过上面的代码) onclick处理程序不会作为其禁用。 要再次启用它,请添加$("#FullName").removeAttr('disabled'); 在另一个按钮或字段的onclick处理程序中。

 $('#checkbox-id').click(function() { //If checkbox is checked then disable or enable input if ($(this).is(':checked')) { $("#to-enable-input").removeAttr("disabled"); $("#to-disable-input").attr("disabled","disabled"); } //If checkbox is unchecked then disable or enable input else { $("#to-enable-input").removeAttr("disabled"); $("#to-disable-input").attr("disabled","disabled"); } }); 

启用/禁用输入场的另一种简单方法

 $("#anOtherButton").click(function() { $("#FullName").attr('disabled', !$("#FullName").attr('disabled')); }); 
   

这应该做到这一点。

 $("#FullName").attr('disabled', 'disabled'); 

Shiplu是正确的,但是如果你没有使用jquery 1.6+,请使用它

 $("#anOtherButton").click(function(){ $("#FullName").attr('disabled', 'disabled'); }); 
  • .attr(attributeName,value)函数

为匹配元素集设置一个或多个属性

要在禁用和启用之间切换字段,请尝试以下操作:

 $('#toggle_button').click(function () { $('#FullName').prop("disabled", function (i, val) { return !val; }); })