选择下拉框指定选项后无法为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
changeevent fires every time the user selects a new option, triggering our function to update the textarea. - Setting
requiredProperty: UsingaddInfo.required = true/falseis more reliable thanremoveAttributefor boolean attributes likerequired. 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
相关产品推荐
相关产品推荐

