Search code examples
javascripthtmlradio-buttononchangerequired

make a input field required if radio is checked


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>

Solution

  • Easy to achieve with jQuery:

    $('#ladder').change(function () {
        if($(this).is(':checked') {
            $('#ladder-meters').attr('required');
        } else {
            $('#ladder-meters').removeAttr('required');
        }
    });