April 18, 2011

Adding submit event on form prevents submit parameter from being included in HTTP POST

Question by Andy

Just what the question title says. I’m using SpringMVC, but that’s irrelevant really. I just need to be able to pass the submit button name=value along with the rest of the form parameters for validation and control purposes. Example below for clarification:

The HTML I’m using:

<form action='somepage.htm' method='post'>
  <input name='somename' value='bob' />
  <input type='submit' name='mybutton' value='click me' />
</form>

The JavaScript (with jQuery) I’m using:

$('form').submit(function() {
  $('input[type="submit"]', this).attr('disabled','disabled');
  return true;
}

And so the HTTP POST request looks like this without the JavaScript event binding:

somepage.htm?somename=bob&mybutton=click%20me

And with the bound event, it excludes the button parameter as such:

somepage.htm?somename=bob

I need to be able to disable the buttons and still send the button value to the server for processing.

Thanks!

SOLUTION:

The code I actually used to solve this problem is:

$(document).ready(function() {
  $('input[type="submit"]').click(function() {
    var clone = $(this).clone();
    $(clone).attr("type","hidden");
    $(this).attr('disabled','disabled');
    $(clone).appendTo($(this).parents('form')[0]);
    return true;
  });
});

And in case anyone was wondering, pressing Enter on a field in the form does in fact trigger the click event on the first submit button in the form!

Answer by Chris

Disabled inputs cannot be submitted.

http://www.w3.org/TR/html4/interact/forms.html#h-17.12

So maybe the way to go is to add a hidden element <input type='hidden' value='foo' name='bar'/> to stimulate the validation methods on the other end.

Answer by Starx

I think, if the submit button is clicked, then it’s values will also be submitted, like rest of the form.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!