选中复选框时启用文本字段

enable the text field when check box is checked

本文关键字:文本 字段 启用 复选框      更新时间:2023-09-26

$("#owncar").click(function() {
  if ($(this).is(':checked')) {
    $("#carnumber").attr('disabled', false);
  } else {
    $("#carnumber").val('');
    $("#carnumber").attr('disabled', true);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<tr>
  <td>Have own car :</td>
  <td>
    <input type="checkbox" name="owncar" id="owncar" value="Y" />
  </td>
</tr>
<tr>
  <td>Car Number :</td>
  <td>
    <input type="text" name="carnumber" id="carnumber" maxlength="10" disabled/>
  </td>
</tr>

当用户从拥有自己的汽车中勾选复选框时,启用车号文本字段以允许用户填写车号。
上面的代码对我来说没问题。单击复选框时,还有其他方法可以启用文本字段吗?

使用 prop() 设置复选框的checked状态。若要设置文本框的值,请使用带回调的val()

// Use change event on the checkbox
$("#owncar").change(function() {
    // Cache checked status
    var checked = this.checked;
    // If checkbox is checked, enable the textfield
    // else disable
    $("#carnumber").prop('disabled', !checked).val(function(i, oldVal) {
        // If the checkbox is not checked, then empty the value
        return checked ? oldVal : '';
    });
});