Have you ever wanted to add a button to your HTML form that doesn't trigger the form submission? Perhaps you want to create a button that performs a separate action without sending the form data to the server. In this guide, we'll walk you through how you can easily achieve this using simple HTML and JavaScript.
By default, when you click a button within an HTML form, it will trigger the form submission. To prevent the form from being submitted when a specific button is clicked, you can change the button type to "button" instead of the default "submit."
Here's an example of how you can create an HTML button that doesn't submit the form:
<button type="submit">Submit</button>
<button type="button">Custom Action</button>
In this snippet, the first button has the default type "submit," which means clicking it will submit the form. The second button has the type "button," which prevents the form from being submitted when clicked.
To add custom functionality to the non-submitting button, you can use JavaScript. In the example above, we've added an `onclick` event that calls a JavaScript function named `customAction()`. You can define this function to perform any custom action you want, such as displaying a message or updating the page content.
Here's how you can define the `customAction()` function:
function customAction() {
alert("Custom action performed!");
// Add your custom code here
}
By adding this script to your HTML document, the `customAction()` function will be called when the non-submitting button is clicked. You can modify this function to suit your specific requirements and implement any desired functionality.
It's essential to remember that using a button with the type "button" instead of "submit" can be helpful for creating interactive forms that require different actions based on user input. This technique gives you more control over the form's behavior and allows you to create a more dynamic user experience.
In conclusion, by changing the button type to "button" and utilizing JavaScript, you can easily create an HTML button that doesn't submit the form. This approach is useful for adding custom actions to your forms while maintaining flexibility and control over the submission process.