I am wondering how I can have a checkbox remove the 'required' validation for a specific radio group in a form.
If the checkbox is checked, I don't want the 'required' attribute to be enforced.
Here is an example of my existing HTML: https://codepen.io/anon/pen/PrbOPK
<label for="Group1_notRequired">Check here to make radio buttons in Gorup 1 NOT required:</label> <input id="Group1_notRequired" name="Group1_notRequired" type="checkbox" value="Group1_notRequired" />
<br><br><br>
<label><input name="Group1" required="" type="radio" value="Option1" />Group 1 Option 1</label>
<label><input name="Group1" required="" type="radio" value="Option2" />Group 1 Option 2</label>
<br><br><br>
<label><input name="Group2" required="" type="radio" value="Option1" />Group 2 Option 1</label>
<label><input name="Group2" required="" type="radio" value="Option2" />Group 2 Option 2</label>
You can use .removeAttr() and .attr() to remove/add an attribute:
$('#Group1_notRequired').on('change', function(e) { if (this.checked == true) { $('[name="Group1"]').removeAttr('required'); } else { $('[name="Group1"]').attr('required', ''); } console.log($('[name="Group1"]').parent()[0].outerHTML); })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label for="Group1_notRequired">Check here to make radio buttons in Gorup 1 NOT required:</label> <input id="Group1_notRequired" name="Group1_notRequired" type="checkbox" value="Group1_notRequired" /> <br><br><br> <label><input name="Group1" required="" type="radio" value="Option1" />Group 1 Option 1</label> <label><input name="Group1" required="" type="radio" value="Option2" />Group 1 Option 2</label> <br><br><br> <label><input name="Group2" required="" type="radio" value="Option1" />Group 2 Option 1</label> <label><input name="Group2" required="" type="radio" value="Option2" />Group 2 Option 2</label>
my suggestion:
$radioG1 = $('[name="Group1"]')
$cbxG1 = $('#Group1_notRequired')
$cbxG1.change(function() {
$radioG1.prop("required", !this.checked)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.