The focus event fires when a form control receives focus, whether by mouse, touch, keyboard navigation, or script. The original example uses three fields and fills the third field with Name when it receives focus.
const nameInput = document.getElementById("name");
nameInput.addEventListener("focus", () => {
if (nameInput.value === "") {
nameInput.value = "Name";
}
});
<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>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Demo onFocus textbox input</title></head>
<body>
<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>
<script>
const nameInput = document.getElementById("name");
nameInput.addEventListener("focus", () => {
if (nameInput.value === "") {
nameInput.value = "Name";
}
});
</script>
</body>
</html>
The example only inserts the value when the field is empty. Modern forms often use a placeholder or nearby help text instead, because automatically changing a field on focus can surprise users. The focus event is still useful for help text, validation hints, selection, and other UI changes.
Event Handling onKeyPress Mouse event Textarea onClick event
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.