You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过复选框同时禁用textarea与input文本框?附现有代码

Solution to Disable Both Textarea and Input Text on Checkbox Toggle

Got it, let's fix this step by step. First off, I notice you've got two elements (textarea and input) sharing the same id="new_order" — that's invalid HTML because IDs must be unique on a page. That's probably causing some unexpected behavior already, so we'll fix that first, then update the function to target both elements.

Step 1: Fix the duplicate ID in HTML

Give your input text box a unique ID (like new_order_input) to comply with HTML standards:

<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked,'new_order','new_order_input')">
<textarea name="noa" id="new_order">FOOO</textarea>
<input type="text" name="noo" id="new_order_input">

Step 2: Update the toggleDisabled function to handle multiple elements

Modify the function to accept multiple element IDs, then loop through them to apply the readOnly (or disabled) state:

function toggleDisabled(_checked, ...elementIds) {
  // Loop through each provided ID to target elements
  elementIds.forEach(id => {
    const element = document.getElementById(id);
    if (element) {
      // Set readOnly to the opposite of the checkbox's checked state
      // Replace `readOnly` with `disabled` if you want to gray out elements and block form submission
      element.readOnly = !_checked;
    }
  });
}

Alternative: Scalable Class-Based Approach

If you might add more elements to toggle later, using a shared class is cleaner than passing multiple IDs:

HTML:

<input type="checkbox" name="no" value="1" onchange="toggleDisabled(this.checked)">
<textarea name="noa" id="new_order" class="toggleable-field">FOOO</textarea>
<input type="text" name="noo" id="new_order_input" class="toggleable-field">

JavaScript:

function toggleDisabled(_checked) {
  // Grab all elements with the shared class
  const fields = document.querySelectorAll('.toggleable-field');
  fields.forEach(field => {
    field.readOnly = !_checked;
    // Use field.disabled = !_checked; if you prefer the disabled UI state
  });
}

Quick Note on readOnly vs disabled

  • Use readOnly if you want users to view/copy content but not edit it (the element stays "active" visually).
  • Use disabled if you want to gray out the element and exclude it from form submission.

内容的提问来源于stack exchange,提问作者SNaRe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:51