I have the following code on my web page:
<form>
<input type="checkbox" id="myCheckbox2" />
first: <input type="text" id="fname" name="fname" >
<input type="text" />
Last:<input type="text" id="lname" name="lname">
<button type="submit">Submit</button>
</form>
when the user clicks on the checkbox with Id= myCheckbox2 then I want the input box fname and lname to be required. I have several other checkboxes and text boxes on my page so i want to get the input box by the id. Below is what I tried:
<script>
var $myCheckbox = $('#myCheckbox2'),
$(document).ready(function() {
$('.checkbox').change(function() {
if ($('.inputBox').attr('required')) {
$('.inputBox').removeAttr('required');
}
else {
$('.inputBox').attr('required','required');
}
});
});
</script>
the above code is making all the input boxes to be required.
2
Answers
You can just use change event on the required checkbox and for adding required to your inputs you can use
$('[name=lname],[name=fname]').prop('required', $(this).is(':checked'));
Demo Code:
Pleas try this code: