JavaScript set input field value

In this tutorial we will learn how to Set input field value with JavaScript. We can use JavaScript value Property and setAttribute() method to set the value of HTML input tag.

value property

value property sets or returns the value of the input field.

In this example value property is used to set the value of input tag.

setAttribute() method

setAttribute() method sets the value of the attribute of the selected HTML element.

We can also use setAttribute() method to set the value of input field.

HTML Code

HTML Code is given below, in this code we have a input field and a button tag with onclick event.

<!DOCTYPE html>
<html>
<head>
<title>JavaScript input value set</title>
</head>             
<body>
    
<input type="text" id="input">
<br><br>    
<button onclick="setInputValue()">Set Input Value</button>    
    
<script src="script.js"></script>    
</body>
</html>

JavaScript Code

Take a look at the JavaScript code, In this code user defined function setInputValue() will set the value of input field.

getElementById() method is used to select the input tag.

value property gives it a new value.

<script>
function setInputValue()
{
    // using value property
    var input = document.getElementById('input');
    input.value = "New Value";
}
</script>

Same code but with setAttribute() method.

<script>
function setInputValue()
{
  // using setAttribute() method
  var input = document.getElementById('input');
  input.setAttribute("value","New Value"); 
}
</script>

Demo

Video Tutorial

Watch video tutorial on How To set input field value using JavaScript.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color