Search code examples
javascripthtml

Cannot get JavaScript to submit a form when conditional is met


I am trying use JavaScript to make sure the four inputs in a tag all match each other and if they do to submit the form or at least allow the form to submit. However, even if the else condition is satisfied the form will not submit.

$(document).ready(function() {
  $('#bca').submit(function(e) {
    var form = bca;
    e.preventDefault();
    // Check Passwords are the same
    if ($('#InitialsP1').val() != $('#InitialsP2').val() || $('#InitialsP2').val() != $('#InitialsP3').val()) {
      alert('Fields do not match. Correct Fields where necessary');
    } else {
      document.getElementById("bca").submit();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="invoice-box">
  <form id="bca" action="bca" method="post">
    <input id="InitialsP1" name="InitialsP1" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP2" name="InitialsP2" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP3" name="InitialsP3" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <input id="InitialsP4" name="InitialsP4" type="text"
          placeholder="Initials" size="5" value="" required 
          style=”float: right”>
    <div class="form-group">
      <div class="col-md-12 text-center">
        <button id="submit" type="submit" class="btn btn-primary btn-lg">Submit</button>
      </div>
    </div>
  </form>
</div>


Solution

  • You have an initial problem in that onclick="getSignature();" is throwing an error because it doesn't exist.

    You're also getting an error "submit is not a function" in your console log when you submit the form (you can see this when you submit the form from your code snippet):

    {
      "message": "Uncaught TypeError: document.getElementById(...).submit is not a function",
      "filename": "https://stacksnippets.net/js",
      "lineno": 46,
      "colno": 38
    }
    

    It's some kind of conflict with the id="submit" on your submit button causing the form not to submit. If you change your submit button html to

    <button id="btn-submit" type="submit" class="btn btn-primary btn-lg">Submit</button>
    

    it should work.