Explain Codes LogoExplain Codes Logo

How To Determine Which Submit Button Was Pressed, Form onSubmit Event, Without jQuery

javascript
event-handling
form-submission
javascript-techniques
Nikita BarsukovbyNikita Barsukov·Feb 16, 2025
TLDR

Jessie, get the secret message (aka clicked button) from using a distinct value in the button's onclick handler and updating the hidden vault (hidden input field) before form submission.

<form id="oh-so-fancy-form" onsubmit="return secretAgent();"> <input type="hidden" id="secret-message" name="action" value=""> <button type="submit" onclick="document.getElementById('secret-message').value='save'">Save</button> <button type="submit" onclick="document.getElementById('secret-message').value='delete'">Delete</button> </form>

On the event of a mission (form submission), the code in 'secret-message' will indicate which button was pressed ('save' or 'delete'). This method doesn't need any special gizmos or spy glasses (additional functions).

Rocking the onSubmit Event

How does a secret agent handle a mission? With a solid strategy (onSubmit handler function).

function secretAgent() { var missionCode = document.getElementById('secret-message').value; alert('Mission code: ' + missionCode); // Interpret the mission code here return false; // Secret agent style. "I never leave a trace." }

This function lets you get a jump on the mission and plan your moves before the mission (form) actually begins.

Understanding Button Clicks

Click handlers: your secret weapon

Your click handlers are like grappling hooks, latching onto the button every time it is clicked.

var lastButtonClicked; // Secret agent grappling hook handler function grappleHook(value) { lastButtonClicked = value; document.getElementById('secret-message').value = value; }

These grappling hooks (onclick handlers) can be fired from each button by passing a distinct code:

<button type="submit" onclick="grappleHook('save')">Save</button> <button type="submit" onclick="grappleHook('delete')">Delete</button>

Cross-browser? More like Cross-continental.

Like accommodating different languages in a multilingual mission, you have to make sure your code works across various browsers. Therefore, always test your solution in different browsers to ensure nobody gets lost in translation.

Accessing Form Elements: don't go in blind.

Equivalent to obtaining a detailed lay of the land before a mission, you can access the particulars of your form through its unique ID:

var fancyForm = document.getElementById('myForm');

This strategy helps you code with conviction without getting lost in the crowd.

Preserving Original HTML: leave no fingerprints.

Blend your event handlers with the surrounding HTML environment without leaving traces of JavaScript on your buttons' original HTML.

Another way to differentiate: button-name superpowers

You can assign a unique name attribute for each button. In data lingo, it's like giving each field agent a codename:

<button name="action" value="save" type="submit">Save</button> <button name="action" value="delete" type="submit">Delete</button>

The command passed can be identified inside the form's onSubmit event, even if no specific command was passed:

function secretAgent(event) { var commandReceived = this.action.value || 'save'; // Default to 'Save' console.log('Received command is:', commandReceived); return false; // "I didn't come here to actually submit the form" }

Handling Form Responses... With Style

JavaScript's Promises and async functions are like elite agents tasked with handling operations after the data is processed:

async function eliteFormAgent(event) { // Shh! Top-secret operations here const response = await fetch('/submit', { method: 'POST', body: new FormData(event.target), }); // Engage protocol: handle response const result = await response.json(); console.log('HQ reports:', result.message); }

Common Issues... or Spy Mission Challenges

Some potential issues (spy movie plot twists) to be aware of:

  1. Synchronization: Ensure the secret-message is set before the onSubmit event fires (make sure the explosives are set before you escape).
  2. Event Propagation: Make sure clicking the button also triggers the form's onSubmit event (the secret handshake must include a firm grip and eye contact).
  3. Form Accessibility: Make sure access to each button is easy, including for keyboard users (every agent, no matter their speciality, needs easy access to gear).