How to Send Value of Button in Form

To send the value of a submit button in an HTML form on a POST or GET request, convert the button element into an input and set the value to send in the value="" attribute.

 

Let's demonstrate this with a simple example.

 

<form method="post" action="/post">
  <input type="submit" name="btn" value="Yes" class="">
</form>

 

In the above example, the property btn with the value Yes will be sent server-side with the rest of the form data via the /post URL.

 

Multiple Submit Button Value in a Form

To have multiple submit buttons in a form and send the value of the one that was clicked, give each submit button the same name with different values like this:

 

<form method="post" action="/post">
  <input type="submit" name="btn" value="Yes" class="">
  <input type="submit" name="btn" value="No" class="">
</form>

 

When either the yes or no button is clicked only that value will be sent with the rest of the form data.

 

How to Send Submit Button Value in AJAX Form Submission

If you are using AJAX to send form data server-side and serialize the form data, you'll need to find the button that was clicked and add its value to the rest of the form data.

 

The example below uses jQuery to find which submit button is focused at the time of submission and adds its value to the serialized form data.

 

// AJAX form submit

$('.ajax').submit(function(e) {
   e.preventDefault();
   
   let form = $(this);
   let data = form.serialize();
   let action = form.attr('action');

   // Add submit button val to serialized form data.
   var btn = $(this).find("input[type=submit]:focus");
   data += '&submit=' + encodeURIComponent(btn.val());

   //... continue with the rest of the AJAX post request...