Abhishek Zirota Abhishek Zirota - 1 month ago 7
Javascript Question

Javascript code: I want the text box to be empty when on focus

I want the text dissappear when the username box is clicked, am I doing it right with onfocus? what am I doing wrong, please help.



document.getElementById("username").onfocus = function() {
document.getElementById("username").value = "";
}

<form name="Sign Up">
<fieldset>
<legend><i><b>Siqn Up</b></i>
</legend>
<p>
<label for="username">Username</label>
<input type="text" value="Unique ID" name="username">
</p>
<p>
<label for="email">Email</label>
<input type="text" name="email">
</p>
<p>
<label for="password">Password
<input type="password" name="password">
</label>
</p>
<input type="submit" value="Sign Up">
</fieldset>
</form>




Answer

The text box only has a name of "username". You need to give it an id attribute as well.

<input type="text" value="Unique ID" name="username" id="username">

Notice how the javascript function is called getElementById? :) That means it needs an Id!