jQuery 如何设置和移除表单控件的 disabled 和 readonly

在 jQuery 中用 .prop('disabled', true) 禁用控件,传入 false 则重新启用。文本输入框和 textarea 可用 .prop('readOnly', true) 设为只读。复选框和 select 不支持 readonly。

disabled 与 readonly 有什么区别

控件 支持 disabled 支持 readonly
input[type="text"] 支持 支持
textarea 支持 支持
input[type="checkbox"] 支持 不支持
select 支持 不支持

禁用的字段无法编辑,通常不能获得键盘焦点,也不会提交。只读文本字段仍可获得焦点和选中文字。如果它处于启用状态且有 name,其值仍会出现在表单数据中。

HTML 标准的 readonly 规则

用 .prop() 切换和恢复状态

把选择器限定在目标表单内。示例先禁用再启用控件,并只对文本字段切换只读。HTML 属性名为 readonly,DOM 属性名为 readOnly。HTML 写成 disabled="false" 仍会禁用,因为该属性存在。恢复时请传布尔值 false。

const $fields = $('#order :input[name]');
const $text = $('#order input[type="text"], #order textarea');

$fields.prop('disabled', true);
$fields.prop('disabled', false);

$text.prop('readOnly', true);
$text.prop('readOnly', false);

jQuery .prop() 官方文档

通过完整示例查看表单数据

将代码以 UTF-8 保存为 form-states.html 并打开。加载 jQuery 4.0.0 需要联网。可编辑状态会显示四个值。选择 readonly 后,标题和备注不能编辑,但四个值仍在。选择 disabled 后所有值都消失。切回可编辑即可恢复。复选框未勾选时,即使启用也不会提交。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较表单控件状态</title>
</head>
<body>
  <label for="mode">状态</label>
  <select id="mode">
    <option value="edit">可编辑</option>
    <option value="readonly">readonly</option>
    <option value="disabled">disabled</option>
  </select>
  <form id="order">
    <p><label>标题 <input type="text" name="title" value="Alpha"></label></p>
    <p><label>备注 <textarea name="memo">Beta</textarea></label></p>
    <p><label>方案
      <select name="plan">
        <option value="basic">基础</option>
        <option value="plus">高级</option>
      </select>
    </label></p>
    <p><label><input type="checkbox" name="news" value="yes" checked> 接收更新</label></p>
    <button id="inspect" type="button">查看表单数据</button>
  </form>
  <pre id="output" aria-live="polite"></pre>
  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
    const form = document.querySelector('#order');
    const $fields = $('#order :input[name]');
    const $text = $('#order input[type="text"], #order textarea');

    function showData() {
      const items = Array.from(new FormData(form));
      const lines = items.map(([name, value]) => name + '=' + value);
      $('#output').text(lines.join('\n') || "表单数据中没有值。");
    }

    function setState() {
      const mode = $('#mode').val();
      $fields.prop('disabled', mode === 'disabled');
      $text.prop('readOnly', mode === 'readonly');
      showData();
    }

    $('#mode').on('change', setState);
    $('#inspect').on('click', showData);
    setState();
  </script>
</body>
</html>

HTML 标准的表单数据构建规则

控件重新启用后仍不可用怎么办

.prop('disabled') 读取第一个匹配元素自身的属性。上层 fieldset 被禁用时,即使控件自身的属性为 false,也可能不可用。用 .is(':disabled') 检查实际状态,再检查上层字段组。如果值缺失,还要确认 name。服务器端应独立校验提交的值。