Alex Rivera | Logout

Pass extra variable when submitting a form using jQuery

Asked 2011-02-23T21:12:42.223
20

I have a form in which the Submit button does not sit within the <form> tags. The submit button has an click handler to submit the form via jQuery's submit() event. This works perfectly.

However, I need the value of the Submit button to be POST'ed as well. Since the button does not exist within the <form> tags, it is not included in the POST array. Therefore, I need to engineer a way to pass an extra variable when the form is submitted.

Some stipulations on what cannot happen to achieve this include:

  • The Submit button cannot be moved within the <form> tags.
  • It cannot use the jQuery ajax, post, or get methods.
  • It cannot have hidden input fields or submit buttons hidden by CSS.
  • The form must act exactly as if there was a normal Submit button in the form.

I envisioned something like, but obviously this does not work.

$('#admin_form').submit({'variable_name', 'true'});

Anybody have any ideas on how I could achieve this?

Edit
Report

1 Answer

34

One thing you could do is use the onsubmit attribute to have javascript inject a post field into the form with the value of the submit button right as it is submitted. You'd have to do this with a hidden input field, but you'd only add the input field right after the user clicked the submit button -- so the input field wouldn't exist there from the beginning (hopefully this satisfies your requirements). So something like:

 function submitHandler()
 {
     submitVal = $('#submitButton').val();
     $('#myForm').append("<input type='hidden' name='submitValue' value='"+
                         submitVal+"' />");
     return true;
 }

Which would stick in the extra value right as the button was clicked.

answered 2011-02-23T21:20:53.663

Your Answer