0
<select required name="shipping_option" id="shipping_option">
  <option selected value="1">1</option>
  <option value="2">2</option>
</select>
    

I have this select and this input

<input  type="text" name="input" placeholder="input">

How I can make this input required when the selected option is 1?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
GBOX
  • 29
  • 4
  • 1
    Does this answer your question? [How to set HTML5 required attribute in Javascript?](https://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript) You'll need an event listener to check the value of the `select` when it changes (https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript), and then you can change the `required` attribute dynamically based on the `select` value (https://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript). – WOUNDEDStevenJones Jan 06 '21 at 18:50
  • 1
    What JavaScript have you tried? – j08691 Jan 06 '21 at 18:51

1 Answers1

1

You can add a change event listener to the select.

const input = document.querySelector('input');
const select = document.getElementById("shipping_option");
input.required = select.value === '1';
select.addEventListener('change', e=>{
  input.required = select.value === '1';
});
Unmitigated
  • 76,500
  • 11
  • 62
  • 80