Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Getting HTML form values and display on console in JavaScript?
In JavaScript, you can retrieve HTML form values using the value property of form elements. This is essential for processing user input and form data.
Basic Syntax
To get a form element's value, use:
document.getElementById("elementId").value
Example: Getting Input Value
Here's how to get a text input value and display it in the console:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Form Values</title>
</head>
<body>
<input type="text" id="getValues" value="My Name is John Smith" />
<script>
var originalValue = document.getElementById("getValues").value;
console.log("The value in the text box is = " + originalValue);
</script>
</body>
</html>
The value in the text box is = My Name is John Smith
Getting Multiple Form Values
For forms with multiple inputs, you can retrieve all values:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple Form Values</title>
</head>
<body>
<form id="userForm">
<input type="text" id="userName" placeholder="Enter your name" value="John Doe">
<input type="email" id="userEmail" placeholder="Enter email" value="john@example.com">
<select id="userCountry">
<option value="USA" selected>USA</option>
<option value="Canada">Canada</option>
</select>
<button type="button" onclick="getFormValues()">Get Values</button>
</form>
<script>
function getFormValues() {
var name = document.getElementById("userName").value;
var email = document.getElementById("userEmail").value;
var country = document.getElementById("userCountry").value;
console.log("Name: " + name);
console.log("Email: " + email);
console.log("Country: " + country);
}
// Get values on page load
getFormValues();
</script>
</body>
</html>
Name: John Doe Email: john@example.com Country: USA
Different Form Element Types
| Element Type | Property | Example |
|---|---|---|
| Text Input | value |
element.value |
| Checkbox | checked |
element.checked |
| Radio Button | checked |
element.checked |
| Select Dropdown | value |
element.value |
Conclusion
Use document.getElementById().value to retrieve form values in JavaScript. This method works for text inputs, dropdowns, and other form elements, making it essential for form processing and user interaction.
Advertisements
