views:

368

answers:

3

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  A: 

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();
});
Gavin Gilmour
+3  A: 

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

VoteyDisciple
A: 

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};
dlamblin