0

I'm trying to validate a form after clicking the submit button, so I'm preventing the form from automatically posting and refreshing the page with preventDefault(). After calling preventDefault(), I call another function to validate, like so:

$("#submit").click(function(e) {

    e.preventDefault();

    validate();

});

Here, #submit is the ID for the submit input element.

At the end of validate(), I try to call submit() on the form element #homeForm, but it doesn't seem to fire.

validate() {

....

console.log('test'); // this is firing

$('#homeForm').submit();
}

I used a few other Stack Overflow answers including this one to arrive at this solution, but I'm not really sure why it's not working. What could be preventing the submit() function from firing?

Edit: I've added a bit of what this form looks like in the HTML

<form id="homeForm">
....

    <input id="submit" class="submit" type="submit" name="submit" value="Submit" action="javascript:void(0);">
</form>
rpivovar
  • 3,150
  • 13
  • 41
  • 79
  • What element has id `homeForm`? Is it a `
    ` element? If so, show it in your question. Are there any other event handlers bound to the `#homeForm` element?
    – Phil Feb 05 '18 at 01:45
  • I've added the form element along with the input submit inside of it. No other event handlers on #homeForm – rpivovar Feb 05 '18 at 01:51
  • 2
    I think you just need to set the action attribute appropriately – kemika Feb 05 '18 at 02:11
  • @kemika wow I totally didn't catch that the action attr was in the complete wrong place. would be glad to mark it correct if you answered once I got home – rpivovar Feb 05 '18 at 02:19
  • you should not put `$('#homeForm').submit();` inside validation function , rather you should call after the validation function. – parlad Feb 05 '18 at 02:19

2 Answers2

2

The form action attribute should belong to the <form> element and should (probably) refer to a url

kemika
  • 134
  • 10
0

The simpler method is to have the submit button call validate() function, then at validate function, if all is validated fine, then submit the form using $('#homeForm').submit(). This way you will never use preventDefault which I feel is the cause for whatever the reason.

Edit: Of course, then your button type should not be 'submit' for this.

Desmond
  • 149
  • 1
  • 2
  • 11