Make the input field necessary if the radio is checked

Is it possible to insert the required attribute in the input field in some way only if a certain radio is checked?

I have an input field called "ladder-meters" that does not need to be filled by default. But if the user checks the switch called “stairs”, the field “stair meters” must be filled.

My input is as follows:

<input type="text" name="ladder-meters" id="ladder-meters"> 

and he should like it at the onchange event on the radio

 <input type="text" name="ladder-meters" id="ladder-meters" required> 
+8
javascript html5 radio-button onchange required
source share
3 answers

Easy to achieve with jQuery:

 $('#ladder').change(function () { if($(this).is(':checked') { $('#ladder-meters').attr('required'); } else { $('#ladder-meters').removeAttr('required'); } }); 
+9
source share
 document.getElementById("ladder").addEventListener('change', function(){ document.getElementById("ladder-meters").required = this.checked ; }) 

Each time you click on the checkmark, the required attribute will be changed in accordance with the check box. To cancel this ratio, replace this.checked with !this.checked

This may require some adjustments according to your specific project.

This will work with this flag:

 <input type='checkbox' id='ladder' name='ladder' /> 
+15
source share

I tried F. Orvalho, did not work for me, I had to use

 $('#ladder').change(function () { if(this.checked) { $('#ladder-meters').prop('required', true); } else { $('#ladder-meters').prop('required', false); } }); 

This may be helpful. thanks to F. Orvalho for the structure

+13
source share

All Articles