How To Get Html Form Data In Javascript

In this blog post, we will learn how to get HTML form data using JavaScript. When creating a web application, it is often necessary to collect data from users through forms. This data can then be used for various purposes, such as validating input, processing the data, or displaying it back to the user.


First, let’s create a simple HTML form with three input fields: name, email, and age. We will also add a button to submit the form:

<form id="myForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

    <label for="email">Email:</label>
    <input type="email" id="email" name="email">

    <label for="age">Age:</label>
    <input type="number" id="age" name="age">

    <button type="button" onclick="submitForm()">Submit</button>

Accessing Form Data using JavaScript

To access the form data, we can use JavaScript’s querySelector and value properties. The querySelector method selects the first element within the document that matches the specified selector. The value property returns or sets the value of the selected element.

Let’s create a JavaScript function called submitForm that will be called when the user clicks the “Submit” button:

function submitForm() {
    const form = document.querySelector('#myForm');

    const name = form.querySelector('#name').value;
    const email = form.querySelector('#email').value;
    const age = form.querySelector('#age').value;

    console.log('Name:', name);
    console.log('Email:', email);
    console.log('Age:', age);

In the above code:

  • We selected the form element using its ID “myForm”.
  • We accessed the input elements inside the form using their IDs and retrieved their values using the value property.
  • We logged the values to the console for demonstration purposes. In a real-world scenario, you would process the data as needed.


In this blog post, we learned how to get HTML form data using JavaScript. We started by creating a simple HTML form with three input fields and a button to submit the form. We then created a JavaScript function that uses the querySelector method to access the form and its input elements. Finally, we retrieved the values of the input elements using the value property and logged them to the console.

Now that you know how to get HTML form data using JavaScript, you can start creating more interactive and dynamic web applications!