Preventing form submission in jquery when for is submitted through javascript .submit

Viewed 44

I am trying to prevent a form submission from happening using the event.preventDefault() in JS. While this works fine on a standard form submission, it seems to not be stopping the submission when the form is submitted externally by JS.

Here is an example HTML form that I am using:

<form id="demo12" method="post">
    <input type="hidden" id="testID" name="testID" value="42">
</form>

<a href="javascript:{}" onclick="document.getElementById('demo12').submit();">Click this sentence to submit the form</a>

And here is the included javascript/jquery file that is trying to catch this form being submitted:

$("[id^='demo']").submit(function (event) {
    event.preventDefault();
    // Then there is some ajax code here
}

Due to the nature of the form being added in through Jinja, there are multiple similar forms. I want to catch any form that starts with 'demo' in the id field and run some AJAX to fetch some new information from the server.

This has worked for me in the past, but the only difference is instead of there being a submit button, the form is being submitted separately through an html hyperlink tag. Is JQuery not able to catch the event of the form submission when it is submitted like this?

Currently when I do this, it just posts the form to the same html page and it the jquery function never occurred. I do see in debugging, through in the browser, that the jquery is listening properly and recognizes the form as something it is listening for to be submitted.

1 Answers

$('[data-submit]').on('click', e => {
  $(e.target.dataset.submit).trigger('submit');
});

$('#demo12').on('submit', e => {
  console.log('you submitted me!');
  e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="demo12" method="post">
    <input type="hidden" id="testID" name="testID" value="42">
</form>

<a href="javascript:{}" data-submit="#demo12">Click this sentence to submit the form</a>

Rather than calling the native submit event, trigger the submit event on the form. This way, you can process it and conditionally cancel it.

Related