Set the Value of an input Field using JavaScript?

To set the value of an input field in JavaScript, you can use the value property. The value property can be used to set as well as to get the current value of an input field.

Let’s say we have the following input field in our HTML:

<input type='text' id='myInput' placeholder='Your name'>

To set the value of this input field, we have to first get the input element using any DOM method such as getElementById() or querySelector(), etc. Next, you can use the value property to set its value.

Here is the related JavaScript code with a live example:

Example:

let val = 'Some default value';

// Invokes on button click
function setValue(){
    document.getElementById('myInput').value = val;
}

And this is how you can get the current value of the above input field using the value property:

let input = document.getElementById('myInput');
console.log(input.value); // Returns input text value

Set input Field Value using setAttribute() Method-

You can also set the value of an input field using the setAttribute() method. The setAttribute() method needs two parameters. First, the name of the attribute, and second the value of the attribute.

See the following working example:

Example:

let input = document.getElementById('myInput');
input.setAttribute('value', 'Some default value');

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.