How to get the values from a form with JavaScript

Updated: 28-Feb-2024 / Tags: Javascript Tutorials / Views: 12456 - Author: George

Introduction

Hello everyone.
In this article we are going to retrieve the values from a form using javascript, store them in an object, and display them on the screen. We are going to see how we can access the values from an input field, a textarea, a select dropdown menu, from radio buttons, and multiple values from checkboxes.

Live Demo

In the demo below, you'll find a form containing all the above mentioned elements. Feel free to interact with the form by selecting or inputting values into the fields. As you do so, observe how the values appear on the right side of the page. For instance, select your favorite color from the dropdown menu and click the submit button to see it in action.

Project's folder

Let's see what files we need to re-create the live example above.

/--project-folder
  |--index.html		
  |--script.js		
  |--styles.css

Create a project folder, and inside create an index.html file to write the HTML code.

Create a script.js file to write the JavaScript code.

And a styles.css file to structure and style the page.

The Index file

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" 
		content="width=device-width, initial-scale=1.0">
	<link rel="stylesheet" href="styles.css">
	<title>How to access form data in javascript</title>
</head>
<body>
	<div class="page">
		
		<!-- Form element -->
		<form name="my-form">
			
			<!-- Input field -->
			<label>Enter your name</label>
			<input type="text" name="firstname">
			
			<!-- Textarea -->
			<label>Write a few words about you</label>
			<textarea name="bio"></textarea>
		
			<!-- Dropdown select menu -->
			<label>Select you favorite color</label>
			<select name="fav-color">
				<option value="">Select a color</option>
				<option value="red">Red</option>
				<option value="green">Green</option>
				<option value="blue">Blue</option>
				<option value="black">Black</option>
			</select>

			<!-- Radio buttons -->
			<div class="radio-buttons">
				<label>Select Gender</label>
				<span>Male</span>
				<input type="radio" name="gender" value="male">

				<span>Female</span>
				<input type="radio" name="gender" value="female">
			</div>

			<!-- Checkboxes -->
			<div class="checkboxes">
				<label>Select the foods you like</label>
				<span>Pizza</span>
				<input class="fav-foods" type="checkbox" 
					name="foods[]" value="pizza">

				<span>Spaghetti</span>
				<input class="fav-foods" type="checkbox" 
					name="foods[]" value="spaghetti">

				<span>Broccoli</span>
				<input class="fav-foods" type="checkbox" 
					name="foods[]" value="broccoli">
			</div>

			<!-- Submit button -->
			<button type="submit" name="submit">Submit</button>
		</form>

		<!-- Output container -->
		<div class="out">
			<code>
				<p>Name:</p>
				<p>Bio:</p>
				<p>Fav color:</p>
				<p>Gender:</p>
				<p>Fav food:</p>
			</code>
		</div>

	</div> <!-- End of page -->

	<!-- Link to the JavaScript file -->
	<script src="script.js"></script> 
</body>
</html>
	

Let's explain how to access with javascript the different form elements that we have in the index.html file.

  • Access the Form Element

    <form name="my-form">

    We gave the form element a name attribute of "my-form", we are going to use the name attribute in the JavaScript file to access the form element, and since we fetching the submitted data using JavaScript there is no need for an "action" or "method" attribute in the form element.


    To access the form element with JavaScript we are going to use the following statement..

    	document.forms

    ..this will return an HTMLCollection that holds every form element that we have in the index page. In our case we have only one.

    	HTMLColection [
    		0: form 
    		my-form: form
    		length: 1
    	]

    We can access the items in an HTMLCollection like we do in arrays. So we can target the index 0 to access our form element ..

    	document.forms[0]

    .. or we can target the form element using the name attribute like this ..

    	document.forms["my-form"]

    An HTMLCollection is a built-in object in the JavaScript Document Object Model (DOM) that represents a collection of elements in an HTML document. It's similar to an array, therefore we can access the elements by targeting their index.

  • Access the Input Form Element

    The input element has its name attribute set to "firstname". We will use the name attribute to access the element's value.

    <input type="text" name="firstname">

    To access the value from an input element, we can write ..

    	document.forms["my-form"].firstname.value
  • Access the Textarea

    We set the textarea's name attribute to "bio". As we did above we will target the name attribute to get the textarea's value.

    <textarea name="bio"></textarea>

    To access the value from a textarea element, we can write ..

    	document.forms["my-form"].bio.value
  • Access the Select menu

    The select menu has a name attribute of "fav-color. We will use the name attribute to get the selected option.

    <select name="fav-color">
    	<option value="">Select a color</option>
    	<option value="red">Red</option>
    	<option value="green">Green</option>
    	<option value="blue">Blue</option>
    	<option value="black">Black</option>
    </select>
    			

    Notice that the name attribute value is separated by a dash "fav-color", this means that in order to access the element by the name we have to use brackets notation [""] like we do when we want to access an item inside an array.

    	document.forms["my-form"]["fav-color"].value
  • Access the Radio Buttons

    When we have more than one radio button in our application we group them together by giving them the same name attribute.

    In our case we set the name attribute to "gender", but they have different values. The first one has the value of "male", and the second one the value of "female".

    <span>Male</span>
    <input type="radio" name="gender" value="male">
    
    <span>Female</span>
    <input type="radio" name="gender" value="female">
    			

    When it comes to radio buttons we can only check one option.


    Again we will access the selected option using the element's name attribute.

    	document.forms["my-form"].gender.value
  • Access the Check boxes

    Unlike the form elements we've encountered so far, we won't be using the name attribute to retrieve the checked values from the checkboxes.

    However, we've set their name attributes to 'foods[]', denoting an array, as a best practice. While this designation is mandatory when using PHP to access the checked values, it's important to note that in JavaScript, this distinction isn't essential.

    <span>Pizza</span>
    <input class="fav-foods" type="checkbox" 
    	name="foods[]" value="pizza">
    
    <span>Spaghetti</span>
    <input class="fav-foods" type="checkbox" 
    	name="foods[]" value="spaghetti">
    
    <span>Broccoli</span>
    <input class="fav-foods" type="checkbox" 
    	name="foods[]" value="broccoli">
    			

    In JavaScript, to access the checked values, we need to assign an attribute with the same value to each checkbox. In our case, all three checkboxes share the same class 'fav-foods'. This class serves as a common identifier that enables us to target and manipulate these checkboxes collectively in our JavaScript code.


    So let's see how we fetch the values from multiple checkboxes .

    let favFoods = document.querySelectorAll(".fav-foods");
    let checkedFoods = [];
    for (let food of favFoods){
    	if(food.checked == true){
    		checkedFoods.push(food.value);
    	}
    }
    			
    1. Select the Checkboxes: We are using the querySelectorAll() method to select all checkboxes with a class of 'fav-foods'.
    2. Create an empty array: We will store in this array the checked values.
    3. Iterate through the checkboxes: We are using an for of loop to iterate through the checkboxes.
    4. Retrieve the Values: If a checkbox is checked, retrieve its value and store it in the checkedFoods array that we have created.
    5. The checkedFoods array now contains the values of the checked checkboxes.

Recreate the Live Demo

Now let's put together al the things that we learned and write the javascript code in the script.js file to recreate the live demo.

let form = document.forms["my-form"];
form.addEventListener("submit", getValues);

function getValues(event){
	event.preventDefault();

	let formData = {
		"name": this.name.value, 
		"bio": this.bio.value, 
		"fav-color": this['fav-color'].value, 
		"gender": this.gender.value,
		"fav-food": []
	}

	let favFoods = document.querySelectorAll(".fav-foods");
	for (let food of favFoods){
		if(food.checked == true){
			formData['fav-food'].push(food.value);
		}
	}

	let	out = `
		<p>Name: <span>${formData.name}</span></p>
		<p>Bio: <span>${formData.bio}</span></p>
		<p>Fav color: <span>${formData['fav-color']}</span></p>
		<p>Gender: <span>${formData.gender}</span></p>
		<p>Fav food: <span>${formData["fav-food"]}</span></p>
	`;

	document.querySelector(".out code").innerHTML = out;
}

Let's break down the above javascript code.

  • Form Selection

    let form = document.forms["my-form"];

    Targeting the form element and store it in the 'form' variable which will give us access to every input element.

  • Adding Eventlistener

    form.addEventListener("submit", getValues);

    An event listener is added to the form element to listen for the "submit" event. When the form is submitted, the function getValues will be called.

  • Form Data Retrieval

    function getValues(event){
    event.preventDefault();
    
    let formData = {
      "name": this.name.value, 
      "bio": this.bio.value, 
      "fav-color": this['fav-color'].value, 
      "gender": this.gender.value,
      "fav-food": []
    }
    			

    The getValues function is triggered upon form submission. It first prevents the default form submission behavior. Then, it creates an object called formData to store the values entered by the user in the form fields. The formData object includes properties for the name, bio, favorite color, gender, and an empty array to store selected favorite foods.


    	this.name.value

    The keyword 'this' gives us access to the methods and properties of the object that it belong to. In this case the keyword 'this' belongs to the form object and we can access by using it all the input elements inside the form.

    It's the same thing as..

    	form.name.value

    or..

    	document.forms["my-form"].name.value
  • Checkbox Processing

    let favFoods = document.querySelectorAll(".fav-foods");
    for (let food of favFoods){
      if(food.checked == true){
         formData['fav-food'].push(food.value);
      }
    }
    			

    We are iterating over each checkbox, checking if it is checked, and if so, we add its value to the "fav-food" array property in the formData object.

  • HTML Output Construction

    let out = `
      <p>Name: <span>${formData.name}</span></p>
      <p>Bio: <span>${formData.bio}</span></p>
      <p>Fav color: <span>${formData['fav-color']}</span></p>
      <p>Gender: <span>${formData.gender}</span></p>
      <p>Fav food: <span>${formData["fav-food"]}</span></p>
    `;
    			

    Here, an HTML output string is constructed using template literals ( back ticks ` ` ) to display the collected form data.

  • Output Display

    document.querySelector(".out code").innerHTML = out;

    The constructed HTML output string is inserted into the HTML element with the class "out code", effectively displaying the form data on the webpage

    And we are done with the javascript code.

The CSS file

Copy and paste the CSS code into your CSS file to apply the structure and style to the page and the form elements. It's the exact same styling as the live demo.

*{
	margin: 0;
	padding: 0;
	box-sizing: border-box;
}

body{
	font-family: sans-serif;
	min-height: 100vh;
	color: #555;
	background-color: white;
}

form{
	border:  thin solid #e4e4e4;
	padding: 20px;
	box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
}

form label{
	display: block;
	margin-bottom: 10px;
	color: #32749a;
}

form input, form textarea{
	display: block;
	width:  100%;
	padding: 10px;	
	font-size: 16px;
	border:  thin solid #e4e4e4;
	margin-bottom: 30px;
}

form select{
	display: block;
	width:  100%;
	margin-bottom: 10px;
	padding: 10px;
	font-size: 16px;
	border:  thin solid #e4e4e4;
	background-color: white;
	color: #555;
}

form input:focus,
form select:focus,
form textarea
{
	outline: none;
}

form textarea{
	min-height: 80px;
}

form input::placeholder{
	font-size: 16px;
}

form button{
	background: #32749a;
	color: white;
	border: none;	
	padding: 15px;
	width:  100%;
	font-size: 16px;
	margin-top: 20px;
	cursor: pointer;
}

form button:active{
	background-color: green;
}

.radio-buttons{
	margin-top: 40px;	
}

.radio-buttons input{
	display: inline-block;
	width: auto;
}

.radio-buttons span{
	padding-left: 20px;
}

.radio-buttons span:nth-child(2){
	padding-left: 0;
}

.checkboxes{
	margin-top: 20px;
}

.checkboxes input{
	width: auto;
	display: inline-block;
}

.checkboxes span{
	padding-left: 20px;
}

.checkboxes span:nth-child(2){
	padding-left: 0;
}

.out{
	font-size: 17px;
	line-height: 28px;
}

.out span{
	font-weight: bold;
	color:  #32749a;
}

.page{
	max-width: 900px;
	display: grid;
	grid-template-columns: 1fr 1fr;
	justify-content: space-between;
	grid-gap: 100px;
	padding: 20px;
	margin: 0 auto;
}

textarea{
	height: 50px;
}		
	

Summary

In this guide, we learned how to use JavaScript to retrieve information from HTML forms. We explored a live demo where we retrieved values from various form elements and displayed them on the screen. Then, we learned how to fetch the values from those elements. Finally, we wrote the JavaScript code to recreate the live demo.

Last Words

Thanks for reading, i hope you find the article helpful.
Please leave a comment if you find any errors, so i can update the page with the correct code.

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉