Programming

jQuery how to get which button was clicked upon form submission

19 September 2026 · 10 min read

jQuery how to get which button was clicked upon form submission

Working with forms and user interactions is a core part of web development, and jQuery simplifies many tasks, including determining which button was clicked during form submission. Understanding how to get which button was clicked upon form submission using jQuery is crucial for creating dynamic and responsive web applications. Imagine a scenario where you have a form with multiple submit buttons, each intended to trigger a different action. Capturing the specific button clicked allows you to tailor your server-side or client-side logic accordingly, enhancing the user experience and streamlining data processing. This article will guide you through the process, providing clear examples and best practices to implement this functionality effectively. We’ll explore various methods, ensuring you can choose the approach that best suits your project’s requirements. Knowing how to extract this information empowers you to create more interactive and user-friendly web forms, making your applications more intuitive and efficient.

Understanding Form Submission and Button Events

Before diving into the jQuery implementation, it’s essential to understand the fundamentals of form submission and button events in HTML. When a user clicks a submit button within a form, the browser triggers a submit event on the form element. This event can then be intercepted using JavaScript, allowing you to prevent the default submission behavior and perform custom actions. Each button can be assigned a unique value, and this value is submitted along with the form data when the button is clicked. Capturing this value is the key to identifying which button initiated the submission.

Furthermore, modern browsers offer robust event handling capabilities that jQuery seamlessly leverages. By attaching event listeners to the form or individual buttons, you can execute specific functions upon form submission. This approach provides flexibility in managing form data, validating inputs, and dynamically updating the user interface. Consider a real-world example: an e-commerce site with multiple “Add to Cart” buttons, each corresponding to a different product. By identifying which button was clicked, the application can accurately add the correct product to the user’s shopping cart. According to a study by Baymard Institute, clear and intuitive form design can increase conversion rates by up to 35% Baymard Institute. Thus, mastering form submission techniques is vital for improving user engagement and achieving business goals.

Different browsers may handle form submission events slightly differently, which is where jQuery provides a consistent and cross-browser compatible interface. By abstracting away these browser-specific nuances, jQuery allows developers to focus on the core logic of their applications, rather than dealing with compatibility issues. Using jQuery’s event handling methods ensures that your code behaves predictably across various platforms and devices. This is crucial for maintaining a consistent user experience and minimizing potential errors. This allows you to extract the appropriate button value when the form is submitted.

Using jQuery to Capture the Clicked Button’s Value

jQuery provides a straightforward way to capture the value of the clicked button during form submission. The primary approach involves attaching a click event handler to each submit button within the form. This event handler captures the button’s value and stores it in a hidden field or a JavaScript variable. This value can then be accessed when the form is submitted, allowing you to identify which button triggered the submission. This method ensures that the correct action is performed based on the user’s interaction. For example, consider a scenario with “Save” and “Cancel” buttons. Capturing the clicked button allows you to execute the appropriate save or cancel logic.

Here’s how you can implement this using jQuery. First, select all the submit buttons within the form using a jQuery selector. Then, attach a click event handler to each button. Inside the event handler, retrieve the button’s value using the $(this).val() method and store it in a variable. This variable can then be used to determine which button was clicked when the form is submitted. The following example demonstrates the basic structure:

$(document).ready(function() { $('form input[type="submit"]').click(function() { var buttonValue = $(this).val(); $('clickedButton').val(buttonValue); // Store in a hidden field }); $('form').submit(function(event) { event.preventDefault(); // Prevent default submission var clickedButtonValue = $('clickedButton').val(); alert('Clicked button: ' + clickedButtonValue); // Perform actions based on clickedButtonValue }); }); 

The code snippet above first attaches a click event listener to each submit button within the form. When a button is clicked, its value is stored in a hidden input field with the ID “clickedButton”. Upon form submission, the code retrieves the value from the hidden field and displays it in an alert box. This demonstrates how you can capture and utilize the clicked button’s value to perform specific actions. This targeted approach helps you ensure that the appropriate logic is executed based on the user’s interaction, which is essential for creating a responsive and user-friendly web application.

Step-by-Step Implementation Guide

To effectively capture the clicked button’s value upon form submission, follow these steps. This guide provides a detailed walkthrough of the implementation process, ensuring you can successfully integrate this functionality into your web applications. Each step is designed to be clear and concise, allowing you to easily follow along and adapt the code to your specific needs. By the end of this guide, you’ll have a solid understanding of how to capture and utilize the clicked button’s value to enhance your form handling capabilities.

  1. Include jQuery Library: Ensure that the jQuery library is included in your HTML file. You can either download the library and include it locally or use a CDN (Content Delivery Network) to link to it.
  2. Create HTML Form: Create the HTML form with multiple submit buttons. Each button should have a unique value that identifies its purpose.
  3. Add Hidden Input Field: Add a hidden input field to the form. This field will store the value of the clicked button.
  4. Write jQuery Code: Write the jQuery code to capture the button’s value and store it in the hidden field when a button is clicked.
  5. Handle Form Submission: Write the code to handle the form submission event. Retrieve the value from the hidden field and perform the appropriate action based on the value.
  6. Test the Implementation: Test the implementation thoroughly to ensure that the correct button value is captured and the appropriate action is performed.

Following these steps ensures a robust and reliable implementation. Remember to test your code thoroughly to catch any potential issues and ensure that the correct button value is always captured. By carefully following these steps, you’ll be able to enhance your form handling capabilities and create more interactive and user-friendly web applications. According to Stack Overflow’s 2023 Developer Survey, jQuery remains a popular choice for web development, highlighting its continued relevance and utility Stack Overflow Developer Survey.

Example Code Snippet

Here’s a complete example incorporating the steps above:

<form id="myForm"> <input type="submit" name="action" value="Save"> <input type="submit" name="action" value="Cancel"> <input type="hidden" id="clickedButton" name="clickedButton"> </form> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { $('myForm input[type="submit"]').click(function() { var buttonValue = $(this).val(); $('clickedButton').val(buttonValue); }); $('myForm').submit(function(event) { event.preventDefault(); var clickedButtonValue = $('clickedButton').val(); alert('Clicked button: ' + clickedButtonValue); // Perform actions based on clickedButtonValue }); }); </script> 

Advanced Techniques and Considerations

Beyond the basic implementation, there are several advanced techniques and considerations to keep in mind when capturing the clicked button’s value. One important aspect is handling dynamic forms, where the buttons are added or removed dynamically using JavaScript. In such cases, you need to use event delegation to ensure that the click event handlers are attached to the buttons correctly. Event delegation involves attaching the event handler to a parent element, such as the form itself, and then filtering the events based on the target element. This approach ensures that the event handler is always active, even for dynamically added buttons.

Another consideration is security. When handling form data, it’s crucial to sanitize and validate the inputs to prevent security vulnerabilities such as cross-site scripting (XSS) attacks. Ensure that the button values are properly encoded before being used in your application logic. Additionally, consider using server-side validation to verify that the received button value is valid and authorized. These security measures are essential for protecting your application and user data. According to OWASP, input validation is a critical security control for web applications OWASP Top Ten.

Here are some key points to remember:

  • Use event delegation for dynamic forms.
  • Sanitize and validate button values to prevent security vulnerabilities.
  • Consider using server-side validation for added security.

Furthermore, consider the user experience. Provide clear feedback to the user when a button is clicked, indicating that their action has been registered. This can be achieved by displaying a loading indicator or updating the user interface to reflect the selected action. By providing visual cues, you can enhance the user experience and make your application more intuitive and responsive. These advanced techniques and considerations will help you create robust, secure, and user-friendly web applications.

Infographic here
FAQ: Frequently Asked Questions -------------------------------
Why is it important to capture the clicked button's value?
Capturing the clicked button's value allows you to perform different actions based on which button the user clicked, enhancing the interactivity and functionality of your web application.
What is event delegation and why is it useful?
Event delegation involves attaching an event listener to a parent element instead of individual child elements. It's useful for handling dynamically added elements, as the event listener is always active, even for new elements.
How can I prevent XSS attacks when handling button values?
Sanitize and validate the button values to remove any potentially malicious code. Use server-side validation to verify that the received value is valid and authorized.
Can I use this technique with other JavaScript frameworks besides jQuery?
Yes, the basic concept of capturing the clicked button's value can be applied to other JavaScript frameworks. However, the specific implementation details may vary depending on the framework's event handling capabilities.
This featured snippet-optimized paragraph concisely answers a common user question: How do I capture the clicked button's value using jQuery? By attaching a click event handler to each submit button, you can retrieve the button's value using `$(this).val()` and store it for later use during form submission. This allows you to tailor your application logic based on the specific button that was clicked, enhancing user experience and improving form handling.
  • Utilize unique values for each button.
  • Store button values in hidden fields for easy access.

Understanding and implementing these techniques empowers you to create more dynamic and responsive web applications. Remember to prioritize security and user experience to ensure a seamless and enjoyable experience for your users. Learn more about web development best practices.

You’ve now gained a comprehensive understanding of how to get which button was clicked upon form submission using jQuery. By leveraging these techniques, you can create more interactive and user-friendly web forms that respond intelligently to user actions. The ability to differentiate between button clicks opens up a world of possibilities for tailoring your application’s behavior and providing a seamless user experience. Take what you’ve learned here and experiment with different form designs and interaction patterns. Consider how these techniques can be applied to other areas of your web development projects. Don’t hesitate to explore further and delve into more advanced jQuery concepts to continue expanding your skills. Why not start by exploring other event handling techniques or diving deeper into form validation methods? The possibilities are endless!

Question & Answer :
I have a .submit() event set up for form submission. I also have multiple forms on the page, but just one here for this example. I’d like to know which submit button was clicked without applying a .click() event to each one.

Here’s the setup:

<html> <head> <title>jQuery research: forms</title> <script type='text/javascript' src='../jquery-1.5.2.min.js'></script> <script type='text/javascript' language='javascript'> $(document).ready(function(){ $('form[name="testform"]').submit( function(event){ process_form_submission(event); } ); }); function process_form_submission( event ) { event.preventDefault(); //var target = $(event.target); var me = event.currentTarget; var data = me.data.value; var which_button = '?'; // <-- this is what I want to know alert( 'data: ' + data + ', button: ' + which_button ); } </script> </head> <body> <h2>Here's my form:</h2> <form action='nothing' method='post' name='testform'> <input type='hidden' name='data' value='blahdatayadda' /> <input type='submit' name='name1' value='value1' /> <input type='submit' name='name2' value='value2' /> </form> </body> </html> 

Live example on jsfiddle

Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?

I asked this same question: How can I get the button that caused the submit from the form submit event?

I ended up coming up with this solution and it worked pretty well:

$(document).ready(function() { $("form").submit(function() { var val = $("input[type=submit][clicked=true]").val(); // DO WORK }); $("form input[type=submit]").click(function() { $("input[type=submit]", $(this).parents("form")).removeAttr("clicked"); $(this).attr("clicked", "true"); }); }); 

In your case with multiple forms you may need to tweak this a bit but it should still apply