Tag Archives: HTML

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.

Submit unchecked checkbox value

I had never noticed before that submitting a form with unchecked checkboxes in it results in those checkboxes not being sent to the server at all. I had always assumed that a zero ( 0 ) would be sent for unchecked since a one ( 1 ) is sent when checked. Rather than add code to specifically handle these individual checkboxes, you can just add hidden inputs above the checkboxes in the HTML with a value of zero like this:

<input type="hidden" name="box1" value="0" /> <input type="checkbox" name="box1" value="1" />

This is a much simpler solution that doesn’t require writing any additional code or sending an array of checkboxes. I chose this method since I was using an automated Settings saver in PHP so it would be a pain to modify it and it could make the code more dirty.

Thanks to iamcam for writing about this.