Display form values after clicking Submit button using event.preventdefault() - jQuery?

For this, use document.getElementById(“”) along with addEventListener().


Following is the code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
   <form id="details">
         <label><input type="text" id="firstName" /> </label>
         <label><input type="text" id="lastName" /> </label>
      <input type="submit">
   const formDetails = document.getElementById("details");
   formDetails.addEventListener("submit", async (ev) => {
      var fName = document.getElementById("firstName").value;
      var lName = document.getElementById("lastName").value;
      console.log("First Name=" + fName);
      console.log("Last Name=" + lName);

To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.

This will produce the following output −

Now, enter value into the text box and click the Submit button.

After clicking the submit button, you will get the following output on console −

Updated on: 09-Nov-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started