0

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

1
  • What happens for users that disable JavaScript? Commented Dec 14, 2014 at 1:49

1 Answer 1

1

If you are using HTML 5, you can using the requiredattribute 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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.