Snowman
Snowman

Reputation: 32061

Using Javascript .focus() highlights text

I have a form like so:

<form action='word.php' name = 'searchbox'>
<input type='text' name='word' id = 'searchbox' value = 'default'>
</form>

In my body I have:

<body onLoad="searchbox.word.focus()">

You can see the fiddle here: http://jsfiddle.net/WEZ7S/

What I'm trying to achieve is just have a blinking cursor at the end of "default", but instead the whole word gets selected instead.

Surprisingly Google hasn't been able to find any solutions. How would I do this?

Upvotes: 0

Views: 2997

Answers (3)

David G
David G

Reputation: 96790

Use setSelectionRange (Chrm, FF):

var len = searchbox.word.length;

searchbox.word.focus();
searchbox.word.setSelectionRange(len, len);

Upvotes: 0

Blender
Blender

Reputation: 298046

You can get around this by resetting the .value property of the element:

searchbox.word.focus();
searchbox.word.value = searchbox.word.value;

There are also less hacky solutions: Use JavaScript to place cursor at end of text in text input element

Demo: http://jsfiddle.net/WEZ7S/1/

Upvotes: 3

ahren
ahren

Reputation: 16961

From a previously answered question: https://stackoverflow.com/a/13371452/1238887

Here's a nifty little trick:

$(document).ready(function() {
    var $field = $("#searchbox"),
        oldVal = $field.val();
    $field.focus().val('').val(oldVal);
});

DEMO: http://jsfiddle.net/X7Y8S/

Upvotes: 1

Related Questions