简体   繁体   中英

Dynamic validation of list of values in Javascript

I have a form with dynamically generated input fields.In these input fields , some items are mandatory and needs to be filled in by the user.While submitting the form , i need to validate the form and check whether the mandatory fields are not empty.How can i achieve this using javascript? Any suggestions are welcome.

Thanks for your valuable time and help

If you are using HTML 5, you can using the required attribute in the input tag else you can use something like below to verify each field before submit.

 $(document).ready(function(){ $("#submit").click(function(){ var failed = false; $(".required").each(function(){ if ($(this).val() == "") { failed = true; } }); if (failed) { alert("Mandatory field is empty!"); } else { alert("Proceed"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form method="post" id="myFomr"> <input name="text1" type="text" class="required" value=""><br> <input name="text2" type="text" value=""><br> <input name="text3" type="text" class="required" value=""><br> <form> <button id="submit" type="button">Submit</button> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM