This post will describe the ways to set the value of the input field using the JavaScript function.
Different Ways to Set Value of Input Using JavaScript Function
To set a value of input using the JavaScript function, use the following approaches:
Method 1: Set Value of Input Using “setAttribute()” Method
Use the “setAttribute()” method for setting the value of the input field. This method is utilized to set the value of a particular attribute on an HTML element. It takes two parameters, the “name” of the attribute and the “value” to set.
Syntax
The following syntax is utilized for the setAttribute() method:
Here, “value” is the name of the input field’s attribute and the second “value” is the desired value to set for the specified attribute.
Example
In an HTML file, create two input fields. One will take input from the user, and in the second input field, the user’s input value will be set dynamically:
<input type="text" id="set" placeholder="Entered value will set here">
Create two variables “inputValue” and the “setValue” that stores the reference of both input fields using the “getElementById()” method:
var setValue = document.getElementById("set");
Invoke the JavaScript pre-built “addEventListener()” method with the input field where the user will enter the value. Then, call the “setAttribute()” method to set the value of user input as the value of the second input field:
setValue.setAttribute("value", inputValue.value);
});
It can be seen that the value entered in the first input field is automatically set in the second input field:
Method 2: Set Value of Input Using “value” Attribute
You can also use the “value” attribute for setting the input value. Assign the value to the attribute which you want to set.
Syntax
Follow the given syntax for the “value” attribute to set the value of input:
Example
Set the entered value of the first input field to the second input field using the “value” attribute in the “addEventListener()” method:
setValue.value = inputValue.value;
});
Output
We have provided all the possible solutions for setting the value of input using the JavaScript function.
Conclusion
For setting the value of input using the JavaScript function, use the “setAttribute()” method or the “value” attribute. The “value” attribute is the most commonly used approach for setting the value of an input. This post described the ways to set the value of the input field using the JavaScript function.