0

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?

Snowman
  • 31,411
  • 46
  • 180
  • 303

3 Answers3

3

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/

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Awesome, this worked in Safari and Chrome but not Firefox. Any way around that? – Snowman Dec 03 '12 at 02:52
  • @mohabitar: Look at the long answer in the question that I linked to. It's a jQuery plugin, so you'll need jQuery to use it. – Blender Dec 03 '12 at 02:54
1

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/

Community
  • 1
  • 1
ahren
  • 16,803
  • 5
  • 50
  • 70
  • @mohabitar - yes it does, I'm on chrome. It's probably because it's a jQuery solution and you were just asking about javascript. See blender's answer for a pure JS workaround. – ahren Dec 03 '12 at 02:56
  • 1
    Ok just got it to work in my code on all browsers after fiddling around, thanks! – Snowman Dec 03 '12 at 03:53
  • Great trick... However, when I use this, it also forces `autofocus` on that field. In my case, I would need to `autofocus` another field, then, for example, if tab were pressed to go to field in question, then the behavior in question would occur... – nicorellius Mar 08 '14 at 22:23
0

Use setSelectionRange (Chrm, FF):

var len = searchbox.word.length;

searchbox.word.focus();
searchbox.word.setSelectionRange(len, len);
David G
  • 94,763
  • 41
  • 167
  • 253