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

选择下拉框指定选项后无法为textarea设置required属性的问题求助

Fixing Textarea Required Attribute Not Updating on Select Option Change

Hey there! I see the issue with your code right away. Let's break it down and fix it step by step.

The Problem

Your current JavaScript code runs only once when the page loads, not when the user selects a new option from the dropdown. That's why choosing *name3 (option3) doesn't trigger the required attribute change or the console log—your code never re-checks the select value after the initial page load.

The Solution

You need to add an event listener to the <select> element that listens for the change event. This way, every time the user picks a new option, your code will run and update the textarea's required status accordingly.

Here's the revised code:

HTML (no changes needed here)

<select class="requiredScript" required>
 <option value="">Select something</option>
 <option value="option1">name1</option>
 <option value="option2">name2</option>
 <option value="option3">*name3</option>
</select>
<textarea placeholder="Enter Additional Information" class="addInfo" rows="8"></textarea>

Updated JavaScript

let addInfo = document.querySelector('.addInfo');
let requiredScript = document.querySelector('.requiredScript');

// Create a reusable function to handle the required attribute logic
function updateTextareaRequirement() {
  if (requiredScript.value === 'option3') {
    addInfo.required = true;
    console.log('it\'s working');
  } else {
    // Using `.required = false` is more consistent than removing the attribute
    addInfo.required = false;
    // If you prefer removeAttribute, you can use: addInfo.removeAttribute('required');
  }
}

// Run the function once on page load to set the initial state
updateTextareaRequirement();

// Listen for changes to the select dropdown and run the function
requiredScript.addEventListener('change', updateTextareaRequirement);

Key Notes

  • Reusable Function: Wrapping the logic in a function lets us run it both on page load and whenever the dropdown changes, ensuring consistent behavior.
  • Event Listener: The change event fires every time the user selects a new option, triggering our function to update the textarea.
  • Setting required Property: Using addInfo.required = true/false is more reliable than removeAttribute for boolean attributes like required. The DOM property directly reflects the element's state, whereas removing the attribute might not always update the element's behavior as expected.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:19:05