Identifying Clicked Submit Buttons in Form onSubmit Event: Pure JavaScript Solutions

Dec 05, 2025 · Programming · 10 views · 7.8

Keywords: Form Submission | JavaScript Event Handling | Cross-Browser Compatibility

Abstract: This article explores techniques to accurately identify which submit button was clicked within HTML form submit event handlers. By analyzing multiple technical approaches, it focuses on the best practice of coordinating click and submit events, provides pure JavaScript implementations without modifying button code, and discusses core principles of browser compatibility and event handling mechanisms.

Problem Context and Challenges

In web development, forms often contain multiple submit buttons, each potentially triggering different business logic. For example, a data editing form might include both "Save" and "Save and Add Another" submit buttons. The developer's core requirement is to accurately determine which button was clicked within the form's onsubmit event handler, enabling appropriate asynchronous operations or subsequent processing.

The technical challenge lies in the fact that standard event objects don't directly provide information about the clicked button when the form submit event fires. While Firefox offers the evnt.explicitOriginalTarget property, this isn't a cross-browser standard solution.

Core Solution Analysis

After comparing multiple technical approaches, the most reliable method involves coordinating click and submit event handling. The core concept is:

  1. Add click event listeners to all submit buttons
  2. Record the clicked button reference in the click event
  3. Use the recorded reference in the submit event

Here's a pure JavaScript implementation based on the best answer:

<script type="text/javascript">
(function() {
    var form = document.getElementById('multiSubmitForm');
    var submitButtons = form.querySelectorAll('input[type="submit"]');
    var clickedButton = null;
    
    // Add click event listeners to all submit buttons
    Array.prototype.forEach.call(submitButtons, function(button) {
        button.addEventListener('click', function(event) {
            clickedButton = this;
        });
    });
    
    // Form submit event handling
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        
        // If no button was explicitly clicked, simulate browser default: select first button
        if (clickedButton === null) {
            clickedButton = submitButtons[0];
        }
        
        // Now execute different logic based on clickedButton
        console.log('Clicked button name:', clickedButton.name);
        console.log('Button value:', clickedButton.value);
        
        // After async operations, manually submit if needed
        // performAsyncOperation().then(function() {
        //     form.submit();
        // });
        
        // Reset clickedButton for next use
        clickedButton = null;
    });
})();
</script>

Technical Principles Deep Dive

The effectiveness of this solution relies on several key principles:

1. Event Propagation Order: When a user clicks a submit button, browsers first trigger the button's click event, then the form's submit event. This deterministic sequence provides a time window to capture button information before the submit event.

2. Variable Scope Design: Using closures or module patterns keeps the clickedButton variable in an appropriate scope, ensuring accessibility in both click and submit event handlers while avoiding global namespace pollution.

3. Browser Default Behavior Simulation: When forms are submitted via keyboard (e.g., pressing Enter), no button is directly clicked. In such cases, most browsers default to the first submit button in document order. Our code simulates this behavior by checking if clickedButton is null, ensuring logical consistency.

Alternative Approaches and Optimization

Beyond the core solution, other answers present different implementation strategies:

Approach 1: Using Form Custom Attributes

<form onsubmit="alert(this.submitted); return false;">
    <input onclick="this.form.submitted=this.value;" type="submit" value="Yes" />
    <input onclick="this.form.submitted=this.value;" type="submit" value="No" />
</form>

This method is concise but embeds JavaScript in HTML attributes,不利于代码维护和关注点分离.

Approach 3: Global Variable Recording

<script type="text/javascript">
var clicked;
function mysubmit() {
    alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
    <input type="submit" onclick="clicked='Save'" value="Save" />
    <input type="submit" onclick="clicked='Add'" value="Add" />
</form>

This approach uses global variables, effective in simple scenarios but potentially causing conflicts and debugging difficulties in complex applications.

Approach 4: Hidden Field Storage

<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $(":submit").click(function () { 
            $("#action").val(this.name); 
        });
    });
</script>

This method stores button information in hidden fields, advantageous for server-side reading but adds DOM manipulation overhead.

Best Practice Recommendations

Based on the analysis, we recommend the following best practices:

1. Event Delegation Optimization: For forms with numerous submit buttons, use event delegation to reduce the number of event listeners:

form.addEventListener('click', function(event) {
    if (event.target.type === 'submit') {
        clickedButton = event.target;
    }
});

2. Asynchronous Processing Integration: In modern web applications, form submissions often involve asynchronous operations. Our solution integrates well with Promises or async/await:

form.addEventListener('submit', async function(event) {
    event.preventDefault();
    
    if (clickedButton === null) {
        clickedButton = submitButtons[0];
    }
    
    try {
        await performAsyncOperation(clickedButton.name);
        // Submit form after successful async operation
        this.submit();
    } catch (error) {
        console.error('Operation failed:', error);
    }
    
    clickedButton = null;
});

3. Accessibility Considerations: Ensure the solution is friendly to keyboard navigation and screen readers. Test behavior when submitting forms via Tab key navigation and Enter key.

4. Browser Compatibility: This solution uses standard DOM event APIs, compatible with all modern browsers (IE9+). For older browsers, appropriate polyfills or fallbacks may be needed.

Conclusion

By coordinating click and submit event handling, we've implemented a reliable solution for identifying clicked submit buttons within form submit events. This approach doesn't rely on browser-specific properties, requires no modification to button HTML code, and maintains good code separation and maintainability. Developers can extend and optimize this foundation based on specific requirements to build more robust form handling logic.

In practical applications, consider encapsulating the relevant logic as reusable modules or components with clear API interfaces for easy integration across projects. Additionally, given the continuous evolution of web standards, monitor developments in related APIs like SubmitEvent for potential adoption of more concise official solutions in the future.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.