Reputation: 803
I have 20 fields in a form some of them are present in multiple divs which are set to display:none
based on some conditions. I want to do a check when user clicks on submit all the visible fields must be required.
Right now have written code on onClick events of few checkboxs but I feel that is not the efficient way to do.. instead if we can run a check by selecting all visible fields on click of submit button as required.
I'll really appreciate any guide for this case?
Upvotes: 0
Views: 844
Reputation: 4912
If you are not dynamically hiding and showing div
s (because a template system does this before the HTML is served), then it is enough to mark all input:visible
fields as required
once, when the page loads.
$("input:visible").prop("required", true)
If you are dynamically hiding and showing div
s (such as in response to button clicks, checkboxes, etc...), you will need to run that line each time fields are hidden or shown.
In this snippet, the first field is visible and the browser warns you if you try to submit when Field 1 is blank; however, the second field is hidden and therefore not marked as required. The browser doesn't complain that it is left blank.
Hope this helps!
// if you dynamically hide/show any fields,
// make sure you re-run this line
$("input:visible").prop("required", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input placeholder="Field 1">
</div>
<div hidden>
<input placeholder="Field 2">
</div>
<input type="submit" value="Submit">
</form>
Upvotes: 2
Reputation: 137
You can match this code as per your requirement. I guess those visible and hidden fields are input types.
$(document).ready(function () {
$("input:visible").each(function () {
$(this).prop("required", true);
});
$("#sbt").on("click", function () {
$('#myForm').find('input').each(function () {
if ($(this).prop('required') && $("#"+this.id).val()=='') {
alert('Please fill the required fields');
return false;
}
});
//your submit code goes here
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm" name="myForm">
<div id="fD">
<input type="text" id="f1" name="f1">
</div>
<div id="sD">
<input type="hidden" id="f2" name="f2">
</div>
<div id="tD">
<input type="text" id="f3" name="f3">
</div>
</form>
<button id="sbt">Submit</button>
Upvotes: 1
Reputation: 378
I assume you hide or show your fields through some form of Javascript. HTML5 elements that you can access in JS can be set to required like so:
document.getElementById("someElement").required = true;
Obviously, the reverse is also possible.
Upvotes: 0