admin管理员组

文章数量:1317906

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

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

Share Improve this question asked Nov 11, 2008 at 19:49 EmmettEmmett 14.3k12 gold badges57 silver badges82 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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.

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.

本文标签: javascriptHow to highlight input text field upon clicking it in SafariStack Overflow