6

I want to have a text input that on focus selects all of the text inside, if any. This is so that I can click on the text input and just start typing rather than having to clear the current value out, assuming I wanted to overwrite what was already in the text input.

How would I do this with jQuery?

3
  • Isn't that the default behavior in most browsers? I just tried it with FireFox, Opera, and IE and they all highlight the content of a text input when I tab into it. Commented Aug 21, 2009 at 21:48
  • Chris, sorry. Looks like you're correct. I can't remember what lead me down the path of hunting this down, but I got so wrapped up in searching that I forgot to just... try it :) Commented Aug 22, 2009 at 14:49
  • Ah, I remember now. The text is not selected when you mouse into the input field. But you are correct, it is the default behavior when you tab into the input field. I will edit the post. Commented Aug 22, 2009 at 19:25

3 Answers 3

8

Couple of links here.

$("#myInputField").focus(function(){
    // Select input field contents
    this.select();
});

// Add this behavior to all text fields
$("input[type=text]").focus(function(){
    // Select field contents
    this.select();
});
Sign up to request clarification or add additional context in comments.

Comments

4

To just select the text, you'd do something like:

$(".inputs-to-which-you-want-to-apply-this-behavior").focus(function() {
  this.select();
});

Another approach, which does not select the text, but rather removes it (only to replace it if you leave the box empty, would look something like this:

$(document).ready(function() {
  $(".inputs-that-currently-have-a-default-value-in-them").each(function() {
    var original = $(this).val();
    $(this).focus(function() {
        if ($(this).val() == original)
          $(this).val('');
    });

    $(this).blur(function() {
      if ($(this).val() == '')
        $(this).val(original);
    });
  });
});

(I prefer this latter approach if the text that's in the box to begin with is placeholder text like 'Enter Your Name' but if what's in the box is, for example, the name I entered last time your original idea of just selecting the text would certainly be better.)

Comments

0

From what I tried out this is the default behavior in most browsers I use.

Though select() function does what others had said it does. Instead I thought it'd work to set the value of the input field to blank if the field was focused.

Something like:

$(":input").focus = function(){if(this.type=="text"){value=""}return true};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.