Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Toggle the Buttons and Submit A Form At The Same Time?
Every HTML form has an action attribute that specifies where form data should be sent when submitted. When working with multiple buttons in a form, you can control their behavior to toggle button states and submit the form simultaneously using JavaScript and different button types.
HTML Buttons
A clickable button is defined by the <button> tag. You can insert text and other HTML elements like <i>, <b>, <strong>, <br>, and <img> inside a <button> element, which is not possible with <input type="button">.
Syntax
Following is the basic syntax for HTML <button>
<form action="#" method="post"> <button type="submit">Submit</button> </form>
For toggling buttons while submitting forms, you can use JavaScript to modify button states
document.getElementById("myButton").disabled = true;
document.getElementById("myForm").submit();
Using JavaScript to Toggle Button and Submit Form
You can toggle button states (like disabling or changing text) while submitting a form by using JavaScript event handlers. This prevents multiple submissions and provides visual feedback to users.
Example Toggle Button Text on Submit
Following example demonstrates how to change button text and disable it when submitting a form
<!DOCTYPE html>
<html>
<head>
<title>Toggle Button on Submit</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<form id="myForm" action="/submit-handler" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<button type="submit" id="submitBtn">Sign In</button>
</form>
<script>
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent actual submission for demo
var button = document.getElementById('submitBtn');
button.textContent = 'Signing In...';
button.disabled = true;
// Simulate form processing
setTimeout(function() {
button.textContent = 'Sign In Complete';
// In real scenario, form would submit here
// this.submit();
}, 2000);
});
</script>
</body>
</html>
When you click the "Sign In" button, it changes to "Signing In..." and gets disabled, then shows "Sign In Complete" after 2 seconds
Initial state: [Sign In] button After click: [Signing In...] button (disabled) After 2 seconds: [Sign In Complete] button
Using Multiple Submit Buttons
You can use the formaction attribute to make different buttons submit to different URLs while toggling their states.
Example Multiple Submit Actions
Following example shows how to use different submit buttons with toggle functionality
<!DOCTYPE html>
<html>
<head>
<title>Multiple Submit Buttons</title>
<style>
.btn { padding: 10px 15px; margin: 5px; cursor: pointer; }
.btn:disabled { opacity: 0.6; cursor: not-allowed; }
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<form id="courseForm" action="/default-action" method="post">
<label for="courses">Choose Course:</label><br>
<select name="courses" id="courses">
<option value="HTML">HTML</option>
<option value="JavaScript">JavaScript</option>
<option value="Python">Python</option>
<option value="CSS">CSS</option>
</select><br><br>
<button type="submit" class="btn" formaction="/enroll" data-action="enroll">Enroll Now</button>
<button type="submit" class="btn" formaction="/preview" data-action="preview">Preview Course</button>
</form>
<script>
var buttons = document.querySelectorAll('.btn');
buttons.forEach(function(button) {
button.addEventListener('click', function(event) {
event.preventDefault(); // Prevent actual submission for demo
var action = this.getAttribute('data-action');
var originalText = this.textContent;
// Toggle button state
this.textContent = action === 'enroll' ? 'Enrolling...' : 'Loading Preview...';
this.disabled = true;
// Simulate processing
setTimeout(function() {
button.textContent = action === 'enroll' ? 'Enrolled!' : 'Preview Ready';
// In real scenario: document.getElementById('courseForm').submit();
}, 1500);
});
});
</script>
</body>
</html>
Each button toggles its text and disabled state when clicked, providing different actions for the same form
Choose Course: [HTML ?] [Enroll Now] [Preview Course] After clicking Enroll: [Enrolling...] (disabled) [Preview Course] After processing: [Enrolled!] [Preview Course]
Toggle Button with Form Validation
You can combine button toggling with form validation to ensure data integrity before submission.
Example Validation with Toggle
<!DOCTYPE html>
<html>
<head>
<title>Form Validation with Toggle</title>
<style>
.error { color: red; font-size: 12px; }
.form-group { margin-bottom: 15px; }
.btn-submit { background-color: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }
.btn-submit:disabled { background-color: #6c757d; }
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<form id="validationForm">
<div class="form-group">
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required>
<div id="emailError" class="error"></div>
</div>
<div class="form-group">
<label for="phone">Phone:</label><br>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>
<div id="phoneError" class="error"></div>
</div>
<button type="submit" id="submitButton" class="btn-submit">Submit Form</button>
</form>
<script>
document.getElementById('validationForm').addEventListener('submit', function(event) {
event.preventDefault();
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var submitBtn = document.getElementById('submitButton');
var isValid = true;
// Clear previous errors
document.getElementById('emailError').textContent = '';
document.getElementById('phoneError').textContent = '';
// Validate email
if (!email || !email.includes('@')) {
document.getElementById('emailError').textContent = 'Please enter a valid email';
isValid = false;
}
// Validate phone
if (!phone || phone.length !== 10) {
document.getElementById('phoneError').textContent = 'Please enter a 10-digit phone number';
isValid = false;
}
if (isValid) {
// Toggle button and submit
submitBtn.textContent = 'Submitting...';
submitBtn.disabled = true;
setTimeout(function() {
submitBtn.textContent = 'Submitted Successfully!';
// In real scenario: form would be submitted here
}, 2000);
}
});
</script>
</body>
</html>
The form validates input fields before toggling the button state. If validation fails, error messages appear and the button remains active
Valid submission: [Submitting...] ? [Submitted Successfully!] Invalid submission: Button remains [Submit Form] with error messages displayed
Best Practices
When implementing button toggling with form submission, consider these practices
Prevent double submission Always disable the submit button after the first click to prevent multiple form submissions.
Provide visual feedback Change button text or appearance to indicate processing status.
Handle errors gracefully Re-enable buttons if submission fails so users can retry.
Use appropriate button types Use
type="submit"for form submission andtype="button"for JavaScript-only actions.
Conclusion
Toggling buttons while submitting forms enhances user experience by providing immediate feedback and preventing duplicate submissions. Use JavaScript event listeners to modify button states, combine with form validation for robust functionality, and always consider user experience when implementing these interactive features.
