How To Determine Which Submit Button Was Pressed, Form onSubmit Event, Without jQuery
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.
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).
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.
These grappling hooks (onclick handlers) can be fired from each button by passing a distinct code:
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:
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:
The command passed can be identified inside the form's onSubmit
event, even if no specific command was passed:
Handling Form Responses... With Style
JavaScript's Promises and async functions are like elite agents tasked with handling operations after the data is processed:
Common Issues... or Spy Mission Challenges
Some potential issues (spy movie plot twists) to be aware of:
- Synchronization: Ensure the secret-message is set before the
onSubmit
event fires (make sure the explosives are set before you escape). - 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). - 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).
Was this article helpful?