Sometimes, we’ve to set the value of an input field in our JavaScript code.
In this article, we’ll look at how to set the value of an input field with JavaScript.
Setting the value Property
One way to set the value of an input field with JavaScript is to set the value
property of the input element.
For instance, we can write the following HTML:
<input id='mytext'>
Then we can set the value
property of the input by writing:
document.getElementById("mytext").value = "My value";
Call the setAttribute Method
Also, we can call the setAttribute
method to set the value
attribute of the input element.
For instance, we can write:
document.getElementById("mytext").setAttribute('value', 'My value');
We call setAttribute
with the attribute name and value to set the value
attribute to 'My value'
.
Setting the value Property of an Input in a Form
We can also get the input element by using the document.forms
object with the name
attribute value of the form and the name
attribute value of the input element.
For example, we can write the following HTML:
<form name='myForm'>
<input type='text' name='name' value=''>
</form>
Then we can use it by writing:
document.forms.myForm.name.value = "New value";
The form name
value comes first.
Then the name
value of the input element comes after it.
document.querySelector
We can use the document.querySelector
method to select the input.
For instance, we can write the following HTML:
<input type='text' name='name' value=''>
Then we can write:
document.querySelector('input[name="name"]').value = "New value";
to get the element with querySelector
.
We select the input with the name
attribute by putting the name
key with its value in the square brackets.
Conclusion
We can set the value of an input field with JavaScript by selecting the element.
Then we can set the value
attribute by setting the value
property or calling setAttribute
.