Set the value of an input field in JavaScript
Last Updated :
02 May, 2024
In JavaScript, there are several ways to set the value of an input field. This guide will provide you with a comprehensive understanding of these methods.
These are the following methods by using we can Set the value of an input field in JavaScript:
1. By using the innerHTML property
Let us discuss the innerHTML Property and how we can set the attribute using this property.
- In this approach, we are going to call a function when the user clicks the button.
- The click event will occur and a function will be invoked.
- The function will get the input value from the input field and add that value using the “innerHTML” property provided by JavaScript.
- At last, that value will be displayed on the screen.
Example: This example is the implementation of the above-explained approach.
html
<!DOCTYPE html>
<html>
<head>
<title>
Set the value of an input field.
</title>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<input type='text' id='id1' />
<br>
<br>
<button onclick="gfg_Run()">
click to set
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
let el_down = document.getElementById("GFG_DOWN");
let inputF = document.getElementById("id1");
function gfg_Run() {
inputF.value = "textValue";
el_down.innerHTML =
"Value = " + "'" + inputF.value + "'";
}
</script>
</body>
</html>
Output:
Set the value of an input field
By using method
Let us discuss the setAttribute Property and how we can set the attribute using this property.
- In this approach, we are going to call a function when the user clicks the button.
- The click event will occur and a function will be invoked.
- The function will get the input value from the input field and set that value using the setAttribute() method.
- And add that value using the “innerHTML” property provided by JavaScript.
- At last, that value will be displayed on the screen.
Example: This example is the implementation of the above-explained approach.
html
<!DOCTYPE html>
<html>
<head>
<title>
Set the value of an input field.
</title>
</head>
<body style="text-align:center;" id="body">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<input type='text' id='id1' />
<br>
<br>
<button onclick="gfg_Run()">
click to set
</button>
<p id="GFG_DOWN" style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
let el_down = document.getElementById("GFG_DOWN");
let inputF = document.getElementById("id1");
function gfg_Run() {
inputF.setAttribute('value', 'defaultValue');
el_down.innerHTML =
"Value = " + "'" + inputF.value + "'";
}
</script>
</body>
</html>
Output:
Set the value of an input field
Share your thoughts in the comments
Please Login to comment...