Tag Archives: post

Programmatically submitting an HTML form via jQuery submit() or trigger(‘submit’) doesn’t work? Solution!

Say you are trying to submit an HTML form via jQuery. If you’re trying to submit it using .submit() or .trigger(‘submit’) you may have ran into a very strange problem where nothing happens for no reason you can figure out. Here is a very basic example below. Why on Earth is this not working?

[code lang=”js” highlight=”12″]

<script type="text/javascript">

jQuery(‘#my-form-submit’).click( function(e) {
e.preventDefault();
// Do some stuff here…
jQuery( ‘#my-form’).submit();
});

</script>

<form action="?ajax=4" method="post" id="my-form">
<input type="submit" name="submit" value="Submit this form!" id="my-form-submit">
</form>

[/code]

 

Browsers reserve some key words for input names, such as “submit”. As you see in line 12 we have name=”submit”. This simple thing is the problem. Just change name=”submit” to name=”my-submit”:

Does not play nicely with jQuery triggering of submit:
[code lang=”js” highlight=”12″ firstline=”12″]

<input type="submit" name="submit" value="Submit this form!" id="my-form-submit">

[/code]

Works:

[code lang=”js” highlight=”12″ firstline=”12″]

<input type="submit" name="my-submit" value="Submit this form!" id="my-form-submit">

[/code]

Unfortunately browsers offer no error or exlanation to the developer as to why triggering the submit is not doing anything. This can be quite frustrating until you figure this tiny aspect out.