views:

1999

answers:

2

I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.

<html>
<body>

<script>
function focusTest(el)
{
   el.select();
}
</script>

<input type="text" value="one" OnFocus="focusTest(this); return false;" />
<br/>
<input type="text" value="two" OnFocus="focusTest(this); return false;" />

</body>
</html>

When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)

A: 

Not sure about a Safari-specific solution here, but an alternative would be to wrap the input element in a div and set the border properties of it via CSS. Then change border color, etc. when focused and unfocused.

Kon
+4  A: 

I noticed Safari is actually selecting the text then removing the selection quickly.

So I tried this quick workaround that works in all browsers:

function focusTest(el)
{
  setTimeout (function () {el.select();} , 50 );
}

Edit :
Upon further testing it turns out the OnMouseUp event is clearing the selection so it is enough to add

onMouseUp="return false;"

to the input element for things to work as they should.

Pat
The OnMouseUP solution works. Thanks!
Emmett
This was a huge help in a similar problem I was trying to debug. I would have never guessed the mouseup event was the culprit. Thanks!
Ryan McGeary