Search code examples
javascripthtmljquery-form-validator

Form not validating with button id using required attribute in javascript


Im trying to validate a form using required attribute,on click of a button, using the 'id' attribute of a button.

If i remove the 'id' attribute, form validates, but with 'id', it isnt validating.

Below is what i have tried:

<form>
 <div class="form-group  text-center">
        <div class="col-sm-12 col-lg-6 col-md-12  m-auto">
            <input type="text" class="form-control input-lg" id="FirstName" placeholder="First Name" name="firstname" required  >
        </div>
    </div>

 <div class="form-group">
        <div class="col-sm-offset-2 col-lg-6 col-sm-12 col-md-12 m-auto">
            <button type="submit" class="btn-lg" id="btnSubmit">Submit</button>
        </div>
    </div>
 </form>

$(document).ready(function () {
     $('#btnSubmit').on("click", function (event) {

    event.preventDefault();
    if (validate()) {
        updateCustomerInfo();
    }
});
});

Solution

  • Instead of click handler attach a submit handler on the form.

    $('#btnSubmit').closest("form").on("submit", function(event) {
    
      event.preventDefault();
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form>
      <div class="form-group  text-center">
        <div class="col-sm-12 col-lg-6 col-md-12  m-auto">
          <input type="text" class="form-control input-lg" id="FirstName" placeholder="First Name" name="firstname" required>
        </div>
      </div>
    
      <div class="form-group">
        <div class="col-sm-offset-2 col-lg-6 col-sm-12 col-md-12 m-auto">
          <button type="submit" class="btn-lg" id="btnSubmit">Submit</button>
        </div>
      </div>
    </form>