How to Change Input Text Value Onclick Event JavaScript

Many times we need to change input value onclick event using javascript. It is quite easy to change the input value of a text field with the DOM element.

DOM is the short form of the Document Object Model, which is helpful to handle any HTML element using JavaScript.

JavaScript Change Input Value On Click Event

Here, we are going to use the .value property of the DOM element to change the value of the input field. It is the straight forward approach to change the text of an input field in javascript.

Example

<!DOCTYPE html>
<html>
<head>
        <title>Change Input Text Value OnClick Event</title>
</head>
<body>
<input type="text" id="my_field" value="errorsea.com">
<button onclick="change()">Change Text</button>
<script>
function change(){
	var txt = "Nick";
	document.getElementById("my_field").value = txt;
}
</script>
</body>
</html>

Read Also: Submit Form Without Submit Button

Explanation

In the above javascript code, we created a function in which we selected the input field using the getElementById() DOM selector and changed its value using .value property. After that we set that function onclick event of a button.

Here, we set a predefined string value which was stored in a JS variable. How ever, we can also pass dynamic values into the input field.

Conclusion

It was quite easy to change input field value using JS right. I hope now you understand the DOM and its value property. There are lots of other DOM properties that vary according to HTML elements. It is suggested to explore them all to master the DOM and event handling.

Enjoy Scripting 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
NG8001_ ‘Mat-Form-Field’ Is Not a Known Element in Angular
[Solved] Error NG8001: ‘Mat-Form-Field’ Is Not a Known Element in Angular CLI

Hey angular geek, if you have the Error NG8001: ‘Mat-Form-Field’ Is Not a Known Element in Angular, you are at...

Close