make a input field required if radio is checked

Morten Hagh picture Morten Hagh · Aug 15, 2012 · Viewed 31.8k times · Source

Can I somehow insert the required attribute into an input field only if a certain radio is checked?

I have an input field named "ladder-meters" that is not required to be filled per default. But if the user checks a radio button that is named "ladder" the "ladder-meters" field are required to be filled.

My input looks like this:

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

and should like this at the onchange event on the radio

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

Answer

lordyoum picture lordyoum · Jun 15, 2015

Tried F. Orvalho, didn't work for me, I had to use

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

It could be usefull. Thx to F. Orvalho for the structure