Select all the text in an input, focusin

I want to have all the text selected when I give the focus to an element.

I used

$('.class-focusin').focusin(function(e) {
    $(this).select();
});

But it's not the perfect behavior I want. When i click between two characters, the input value is not seleted, there is a cursor in the middle. I want the behavior of the url bar in chrome browser: you click and the cursor is replaced by the value selection

Feel free to test my problem in this fiddle: http://jsfiddle.net/XS6s2/8/

I want the text to be able to receive the cursor once selected. The answer selected, below is definitely what I wanted, Thanks


You could have a variable to see if the text has been selected or not:

http://jsfiddle.net/jonigiuro/XS6s2/21/

var has_focus = false;
$('.class-focusin').click(function(e) {
    if(!has_focus) {
        $(this).select();
        has_focus = true;
    }
 });

$('.class-focusin').blur(function(e) {
   has_focus = false; 
});

I guess you have to wait for the browser to give focus to the element, then do your selection:

$('.class-focusin').focus(function(e) { 
    var $elem = $(this);
    setTimeout(function() {
    $elem.select();
    }, 1);
 });

Yuck. Or simply bind to the click event instead:

$('.class-focusin').click(function(e) { 
    $(this).select();
 });

Try using click instead of focusin.

$('.class-focusin').click(function(e) {
    $(this).select();
});

Demo

Bye!

链接地址: http://www.djcxy.com/p/14758.html

上一篇: 我可以在Objective中声明变量吗?

下一篇: 选择输入中的所有文本,focusin