5

HTML

<input id="formloginusername" type="text" name="username" placeholder="Username" value="Pre-filled-from-database"></input>

JS:

$(document).ready(function() {
    $("#formloginusername").focus();
});

Problem:

The text "Pre-filled-from-database" is highlighted. I only want the cursor to show in the field as if the user had clicked it after the filled text.

Thanks!

ahren
  • 16,803
  • 5
  • 50
  • 70
GiantDuck
  • 1,086
  • 3
  • 14
  • 27

3 Answers3

14

Here's a nifty little trick...

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

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

ahren
  • 16,803
  • 5
  • 50
  • 70
  • This is a fantastic example, thank you. Question is: so now you go to your page and it's focused, but say as a user you start typing: it doesn't clear the text, it just adds to it. Ie your value is 'search here!' you type 'college math books', it would be 'search here!college math books'. How to avoid this? EDIT: $("input.search-input-header")[0].reset(); works ok, but only if you click. How do you have the focus set AND when you start typing it clears? – Nubtacular Apr 18 '13 at 07:32
  • 1
    @DavidPardy - If you're not worried about older browsers, I believe you're describing the default behaviour of the `placeholder` attribute. `` – ahren Apr 18 '13 at 08:01
  • I'm a noob and I apologize in advance, but never heard of the placeholder attribute within input tags. I've been Googling for a bit now. My current js is https://gist.github.com/DavidPardy/5411042 . It clears IF you click, but since the focus is set on the search form, I want it to clear as you're typing. – Nubtacular Apr 18 '13 at 08:09
  • 1
    @DavidPardy - Check out this JSFiddle (http://jsfiddle.net/X7Y8S/6/) - the behaviour may be different across the browsers, but check it out on Chrome. I THINK that is what you're after - can you confirm? – ahren Apr 18 '13 at 08:11
  • 1
    Dude, awesome. And I'm sorry if I came off as ignorant, I had literally never heard of placeholder for such a thing before. Thank you! <3 – Nubtacular Apr 18 '13 at 08:15
  • 1
    @DavidPardy - No worries. Nobody knows everything, and there is certainly no shame in asking. – ahren Apr 18 '13 at 08:16
0

Just this will do:

$('#field').focus().val($("#field").val());
Hopstream
  • 6,391
  • 11
  • 50
  • 81
0

Hopstream, what I found in Chrome using your method is the cursor ended up at the end of the text. I needed a way to get the cursor focused on the start of the field without highlighting the text. This worked for me:

$('#ElementID').each(function () { $(this).focus(); this.selectionEnd = this.selectionStart; });

jeff
  • 31
  • 2