In this tutorial, we will learn how to display the HTML form output on the same page using JavaScript. This technique can be useful so that users can see their inputs and any errors on the same page instead of being redirected to a different page.
Steps:
Step 1: Create an HTML Form
To begin, create an HTML form in your WordPress site. Make sure to give each input field a unique id so that we can easily access them later with JavaScript. For example:
1 2 3 4 5 6 7 8 9 |
<form id="myForm"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br> <label for="email">Email:</label> <input type="email" id="email" name="email"><br> <button type="submit" onclick="submitForm()">Submit</button> </form> |
Step 2: Add a Div Element for Output
Next, add a div element to your HTML page where you want the form output to be displayed. Give it a unique id, such as “outputDiv”. For example:
1 |
<div id="outputDiv"></div> |
Step 3: Create a JavaScript Function to Handle Form Submission
Now, create a JavaScript function to handle the form submission. This function will prevent the default form submission behavior and instead display the form output on the same page. For example:
1 2 3 4 5 6 7 8 9 10 |
function submitForm() { event.preventDefault(); // Prevent form from submitting // Get input values var name = document.getElementById("name").value; var email = document.getElementById("email").value; // Display output document.getElementById("outputDiv").innerHTML = "Name: " + name + "<br>Email: " + email; } |
In this example, we first prevent the default form submission behavior using event.preventDefault(). Then, we get the values of the name and email input fields using document.getElementById(). Finally, we display the output in the outputDiv using the innerHTML property.
Step 4: Test the Form
Save your changes and test the form. Enter some text in the input fields and click the Submit button. The form output should be displayed in the outputDiv on the same page.
Conclusion
By using JavaScript, we can display the HTML form output on the same page for a better user experience. This technique can be useful for forms that require validation or for forms where users need to see their inputs and any errors on the same page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<form id="myForm"> <label for="name">Name:</label> <input type="text" id="name" name="name"><br> <label for="email">Email:</label> <input type="email" id="email" name="email"><br> <button type="submit" onclick="submitForm()">Submit</button> </form> <div id="outputDiv"></div> <script> function submitForm() { event.preventDefault(); // Prevent form from submitting // Get input values var name = document.getElementById("name").value; var email = document.getElementById("email").value; // Display output document.getElementById("outputDiv").innerHTML = "Name: " + name + "<br>Email: " + email; } </script> |
Output:
Name: John Doe Email: [email protected]