Saturday, February 19, 2011

How to highlight input text field upon clicking it in Safari?

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.)

From stackoverflow
  • 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.

  • 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.

    Emmett : The OnMouseUP solution works. Thanks!
    Ryan McGeary : 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!

0 comments:

Post a Comment