Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/Ajax does not get submit button name

I am struggling with form submit using multiple submit buttons in the form. I know that the submit button name is not serialized, but I need to pass that name to the processing script.

Sample code:

<form id='newqueryform' action='process-forms.php' method='post' >
    <input type='hidden' name='formname' value='newqueryform'>
    <div id='runit'><input type='submit' name='runit'  value='Run' /></div>
    <div id='saveit'><input type='submit' name='saveit' value='Save' /></div>
</form>

There are 2 submit buttons here, but in the jQuery code:

$('#workarea').on('submit','#newqueryform', function(e)
{           

  var formData = $(this).closest('#newqueryform').serializeArray();
  alert(JSON.stringify(formData));
  ...

The 2 submit buttons don't show!! Only the other input fields show. How do I know which button was pressed??

like image 341
seedhom Avatar asked Mar 13 '13 23:03

seedhom


People also ask

How to submit button jQuery?

jQuery submit() Forms can be submitted either by clicking on the submit button or by pressing the enter button on the keyboard when that certain form elements have focus. When the submit event occurs, the submit() method attaches a function with it to run. It triggers the submit event for selected elements.

How to write form submit in jQuery?

Answer: Use the jQuery submit() Method You can use the submit() method to submit an HTML form (i.e. <form> ) using jQuery. The jQuery code in the following example will submit the form on click of the button (i.e. the <button> element) which has the type attribute set to button (i.e. type="button" ).


1 Answers

Since you're relying on the buttons being clicked rather than just the form being submitted bind the action to the buttons. As $(this) in function(){} is the clicked button you can its details to formData.

$('#workarea').on('click','#newqueryform input[type="submit"]', function(e){
    var formData = $(this).closest('#newqueryform').serializeArray();   
    formData.push({name: this.name, value: this.value});
    ...
like image 56
Nigel Angel Avatar answered Oct 19 '22 19:10

Nigel Angel