views:

393

answers:

1

I want the input fields on my site to select all the text when the user first clicks on them, but in IE8 the text is selected for a split second then reverts back to normal. Works fine in FF.

My js code:

$(document).ready(function () { //HTML DOM document is ready
    // Add this behavior to all text fields
    $("input[type='text'], textarea").live("focus", function(){
                                         // Select field contents
                                         this.select();
                                         });
});

Any ideas? I've tried adding ".focus()" after ".select()" and bizarrely enough it works, but throws loads of js errors in FF and IE.

Thanks

+1  A: 

Try .select() on a jQuery object instead of the DOM element, and change the event to click. When you tab into the field, the text should be selected by default.

$("input[type='text']").live("click", function(){
       // Select field contents
      $(this).select();
  });

Well, this one was kicking me in the rear for some reason. I could swear I've done this before, but couldn't figure it out how.

This is the best I came up with. It postpones the .select() using setTimeout() until after the click event fires. Maybe there's a better way? Hope it helps.

$('input[type=text]').live('focus', function() {
    var $th = $(this);
    setTimeout(function(){$th.select();}, 50);
});
patrick dw
The problem with this is that the field highlights each time I click - so if the user clicks into a field to edit it (say to correct an email address / spelling) they can't prevent the entire field from being selected each time.
katebp
@katebp - One solution might be to track which input has focus in a variable, and test in the `click()` handler if that same field was the last to have focus. If so, no `select()`. I'll update my answer in a minute.
patrick dw
@katebp - Sorry for the delay. Updated my answer. Not sure if it is the best solution, but seems to work in IE8. Let me know how it turns out.
patrick dw
Excellent! Thanks.Not sure why it works (I would have thought the element would be selected even if the "setTimeout(function(){$th.select();}, 50);" was replaced with "$th.select();" but it doesn't..?), but it works!
katebp
@katebp - Yeah, its a strange one. It appears as though the order of events is such that `click` takes place after `focus`, so the click immediately cancels the effect of the `.select()`. Delaying the `.select()` for 50 milliseconds ensures that it takes place *after* the click. Glad it works for you!
patrick dw