How to implement a multi-step form with jQuery



Image not found!!

Implementing a multi-step form using jQuery involves breaking the form into multiple sections and showing/hiding them based on the user's progress. Here's a basic example to get you started:

HTML:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Multi-Step Form</title> <link rel="stylesheet" href="styles.css"> </head> <body> <form id="multi-step-form"> <!-- Step 1 --> <div class="step" id="step-1"> <h2>Step 1</h2> <label for="field1">Field 1:</label> <input type="text" id="field1" name="field1"> <button type="button" class="next-step">Next</button> </div> <!-- Step 2 --> <div class="step" id="step-2"> <h2>Step 2</h2> <label for="field2">Field 2:</label> <input type="text" id="field2" name="field2"> <button type="button" class="prev-step">Previous</button> <button type="button" class="next-step">Next</button> </div> <!-- Step 3 --> <div class="step" id="step-3"> <h2>Step 3</h2> <label for="field3">Field 3:</label> <input type="text" id="field3" name="field3"> <button type="button" class="prev-step">Previous</button> <button type="submit">Submit</button> </div> </form> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="script.js"></script> </body> </html>

CSS (styles.css):

css
body { font-family: Arial, sans-serif; } .step { display: none; } .step h2 { margin-bottom: 20px; } button { margin-top: 10px; }

JavaScript (script.js):

js
$(document).ready(function () { var currentStep = 1; var totalSteps = $('.step').length; // Show the initial step $('#step-' + currentStep).show(); // Function to navigate to the next step $('.next-step').on('click', function () { if (currentStep < totalSteps) { $('#step-' + currentStep).hide(); currentStep++; $('#step-' + currentStep).show(); } }); // Function to navigate to the previous step $('.prev-step').on('click', function () { if (currentStep > 1) { $('#step-' + currentStep).hide(); currentStep--; $('#step-' + currentStep).show(); } }); // Prevent form submission (modify as needed) $('#multi-step-form').submit(function (e) { e.preventDefault(); alert('Form submitted successfully!'); // Add your form submission logic here }); });

This code creates a multi-step form with three sections. Users can navigate between steps using the "Next" and "Previous" buttons. You can customize this example to fit the specific requirements of your form.