In this blog post, we’ll discuss how to get the value of an input field in HTML using JavaScript. This is a common requirement when you need to process user input, like validating form data, adding interactivity to your web pages, or sending data to a server-side script.
1. Basic HTML input field
First, let’s start with the basic HTML code for an input field:
<input type="text" id="inputField" placeholder="Type something here">
This code creates a simple text input field with an id
attribute set to inputField
and a placeholder text that reads “Type something here”.
2. Getting input value using JavaScript
To get the value of the input field, we’ll use JavaScript. Specifically, we’ll write a function that retrieves the input value and displays it in an alert dialog.
Here’s the JavaScript code for our function:
function getInputValue() {
var inputField = document.getElementById("inputField");
var inputValue = inputField.value;
alert("Input value: " + inputValue);
}
Let’s break down the code:
- We define a function called
getInputValue
. - We use the
document.getElementById
method to get the input element with theid
“inputField”. We store the element in a variable calledinputField
. - We get the value of the input field by accessing its
value
property. We store this value in a variable calledinputValue
. - Finally, we display the input value in an alert dialog.
3. Adding a button to trigger the function
To test our JavaScript function, we’ll add a button that calls the getInputValue
function when clicked:
<button onclick="getInputValue()">Get Input Value</button>
4. Complete HTML code example
Here’s the complete HTML code, including the input field, the button, and the JavaScript code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Input Value Example</title>
</head>
<body>
<input type="text" id="inputField" placeholder="Type something here">
<button onclick="getInputValue()">Get Input Value</button>
<script>
function getInputValue() {
var inputField = document.getElementById("inputField");
var inputValue = inputField.value;
alert("Input value: " + inputValue);
}
</script>
</body>
</html>
And that’s it! Now you know how to get the value of an input field in HTML using JavaScript. This technique can be applied to various types of input fields, such as text, email, password, and more.