Categories
JavaScript Answers

How to Change the Placeholder Text of an Input Element with JavaScript?

Spread the love

Sometimes, we want to change the placeholder text of an input element with JavaScript.

In this article, we’ll look at how to change the placeholder text of an input element with JavaScript.

Change the Placeholder Text of an Input Element with JavaScript

To change the placeholder text of an input element with JavaScript, we can set the placeholder property of an element.

For instance, if we have the following input elements:

<input type="text" name="Email" placeholder="Some Text">
<input type="text" name="firstName" placeholder="Some Text">
<input type="text" name="lastName" placeholder="Some Text">

Then we can set the placeholder attribute value for each input element by writing:

document.getElementsByName('Email')[0].placeholder = 'new text for email';
document.getElementsByName('firstName')[0].placeholder = 'new text for fname';
document.getElementsByName('lastName')[0].placeholder = 'new text for lname';

We call document.getElementsByName to get the element with the given name attribute value.

Then we use index 0 to get the first element returned.

Next, we set the placeholder property of each to a string with the new placeholder property value.

And now we see the text we set in the JavaScript code is displayed as the placeholder text.

Conclusion

To change the placeholder text of an input element with JavaScript, we can set the placeholder property of an element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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