A simple way to change the placeholder text using jQuery

By | May 25, 2021

The placeholder is an attribute in HTML that help users to know the expected value of the input field. It is visible to the users until the user enters the value in the input field.

In following example, I have used j Query’s attr() method to change the placeholder text and the scenario is, when the user will click on ‘Click Me’ button then the placeholder of the input box will be changed from ‘Enter your email’ to ‘Enter your phone number’.

The jQuery code to change the placeholder is:

$('#my-textbox').attr('placeholder','Enter your phone number');

and, here is the complete code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Change the placeholder text using jQuery</title>
  <style>
	#parent_div{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
  </style>
</head>
<body>
	<div id="parent_div">
		<input type="text" id="my-textbox" placeholder="Enter your email" />
		<input type="button" id="click_button" value="Click Me" />
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
	$(function() {
	    $('#click_button').click(function(e){
		  $('#my-textbox').attr('placeholder','Enter your phone number');
		});
	});
  </script>
</body>
</html>

The Output:

Before:

After clicking ‘Click Me’ button: