How To

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 >

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 🙂

Nachiket Panchal

Founder & Administrator of `errorsea` Having interest in Programming & Technology.

Recent Posts

5 Important Things To Know About WordPress Before You Use It

There is a reason big-name companies like CNN use WordPress. WordPress is a popular content…

3 years ago

How to Install MySQL on Your PC in 3 Easy Steps

In this tutorial, I'm going to show you how to install MySQL on your computer.…

4 years ago

Download and Install Turbo C++ for Windows 10 (Full Installation Guide)

Download Turbo C++ for windows 10 in just 7 Mb and run your first C++…

5 years ago

PHP .HTACCESS Redirects

We can redirect any webpage to any other or redirect the whole domain or website…

5 years ago

PHP Redirect Pages

There are lots of methods to redirect pages, like refresh-redirect from META tag, redirect from…

5 years ago

PHP Include & Required

Include files in PHP are used in appending various global or config files. We can…

5 years ago