I have an hidden div which will contain some HTML inputs which some are needed to be required as part of a form. the div is visible by checking the checkbox and the code looks like this:
$(function() {
var checkbox = $("#checkbox01");
var hidden = $("#div01");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
} else {
hidden.hide();
$("#username").val("");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input id="checkbox01" name="checkbox01" type="checkbox">show/hide</label>
<div id="div01">
<input name="username" type="text" required>
</div>
You can see the code in action on JSfiddle As you can see the div is hidden when the checkbox is unchecked and also the username is cleaned when the div is hidden (checkbox unchecked).
How can I make the required be added to HTML only if checkbox is checked, so user won't get prompt to enter value when the div is hidden by Jquery... ?