-
Get Focus on text box
Hi Everyone,
Currently, I have a text box that has text in it when it is loaded. for example, one says, "Enter Email Address". I have an onFocus command on the text box that erases the text leaving the text box blank when there is focus on it. However, I also want to have the cursor placed in the box when this happens. I have tried the following code and it erases the text like it should but it does not place the cursor in the text box. How can I get this to work?
Code:
function clear_EmailAddress()
{
if (document.SignIn.txtEmailAddress.value == " Enter Email Address")
document.SignIn.txtEmailAddress.value = "";
document.SignIn.txtEmailAddress.focus();
}
-
hmmm interesting..... so, when you click on the textbox, it clears it out (like it should), but doesn't set the focus there? That seems to defy how it should work. Have you tried it without the .focus command?
Im wondering if it's ending up in a loop. You click on the text box, it gets focus, gets cleared, gets focus, gets cleared, gets focus, etc......
I don't think you need to set the .focus of the text box.
-
It works for me with this code (I change the string to input.defaultValue because it's better that way, but it worked fine the original way too):
Code:
<script type="text/javascript"><!--
function clear_EmailAddress()
{
if (document.SignIn.txtEmailAddress.value == document.SignIn.txtEmailAddress.defaultValue)
document.SignIn.txtEmailAddress.value = "";
document.SignIn.txtEmailAddress.focus();
}
//--></script>
<form name="SignIn"><p>
<input>
<input name="txtEmailAddress" value=" Enter Email Address" onfocus="clear_EmailAddress();">
</p></form>
-
I think it's the absense of returning either true or false. If you happen to be calling the function from the onsubmit event of the form (just an assumption) just need to return true or false...
Code:
<html>
<head>
<title>Untitled</title>
<script language="JavaScript" type="text/javascript">
<!--
function clear_EmailAddress(){
if (document.SignIn.txtEmailAddress.value == " Enter Email Address"){
document.SignIn.txtEmailAddress.value = "";
document.SignIn.txtEmailAddress.focus();
return false;
}
return true;
}
//-->
</script>
</head>
<body>
<form name="SignIn" method="get" onsubmit="return clear_EmailAddress();">
<input type="text" name="txtEmailAddress" value=" Enter Email Address" />
<input type="submit" />
</form>
</body>
</html>
-
uh... i may be oversimplifying...
<input type=text onClick="this.value=''" value="foo!">
-
The problem with that is that it doesn't take into account if the user has got there by keyboard navigation (e.g. tabbing).
-
I think if you set the focus first, and then the value, it will work. When their is no value in the input, maybe no cursor will appear.