如果选中收音机,则需要输入字段

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>

解决方案

Easy to achieve with jQuery:

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

相关文章