Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 249
goto Avatar asked Jul 18 '13 07:07

goto


People also ask

How do you select all text in input?

The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.

How to Select all input in jQuery?

//Select all Input field on focus $("input"). select(); //Select Input field on focus whose type="text" $("input[type='text']"). select(); //Select input field using its id="input-field" $("#input-field"). select();

How to Select input type text in jQuery?

The :text selector selects input elements with type=text.

How do you select text in HTML?

HTML | DOM Input Text select() Method The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();


2 Answers

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; 
});
like image 135
Jonas Grumann Avatar answered Oct 14 '22 14:10

Jonas Grumann


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();
 });
like image 39
CodingIntrigue Avatar answered Oct 14 '22 15:10

CodingIntrigue