How to Change Input Text Value Onclick Event JavaScript

Many times we need to change the input text 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.

Change Input Value OnClick 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 *

More in How To, JavaScript
Get All the Selected Checkbox Values jquery
How to Get All the Selected Checkbox Values Onclick Using jQuery

Checkboxes are quite useful in web forms. Even more, jQuery provides a handy functionality to manage checkboxes. Here, we are...

Close