Text Input Focus Event Demo

Tab through the three fields or click the Your Name field. The original demo behavior is preserved: an empty name field receives the value Name.



Return to tutorial on text onfocus

JavaScript

const nameInput = document.getElementById("name");

nameInput.addEventListener("focus", () => {
  if (nameInput.value === "") {
    nameInput.value = "Name";
  }
});

HTML

<form id="profile-form" action="" method="post">
  <label>Your Userid <input type="text" name="t3"></label><br>
  <label>Your Password <input type="password" name="t2"></label><br>
  <label><strong>Your Name</strong> <input type="text" id="name" name="t1"></label>
</form>