Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text on focus

I'm trying to select the text in a readonly input box, using jQuery, this is what I have:

    $('input').focus(function(){
        $(this).select();
    })

When I click on the input however, it quickly selects all the text, it "blinks", then it goes back to normal state of being unselected.

Any ideas around this?

like image 833
dzm Avatar asked Jun 24 '11 15:06

dzm


People also ask

How do you select all text in input on focus?

select to select all the text in the input as the value of the onFocus prop. e. target is the input element so we can call select on it to select all the text.

How do you select content 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();


3 Answers

 <input onClick="this.select()" value="Blabla und Blublu" type="text" />

Should work

like image 53
Mexx Avatar answered Sep 28 '22 09:09

Mexx


There's a little bit of an oddity happening here. focus happens on mousedown, but cursor placement happens on click (i.e. a mousedown followed by a mouseup). When the cursor is placed, any selection goes away.

So, you'll most likely want to keep your focus event (for tabbing and triggering purposes) but also add a click or a mouseup handler to do the actual select in the case of a click.

$('input[type="text"]').focus(function() {
    $(this).select();
}).click(function() {
    if ($(this).val() === 'Your default value')
    {
        $(this).select();
    }
});

The if exists so that once a user has customized text in your input, they can click around without selecting text. Although, that doesn't really apply to a readonly text input, so it may be safely removed.

Edit: Code seems to be inconsistent at best, so this may not be the solution.

like image 34
Ryan Kinal Avatar answered Sep 28 '22 08:09

Ryan Kinal


I got it working using the below code . My chrome version:Version 24.0.1312.52

$("#inputid").on("focus",function(e){
    $(this).select();
});

$("#inputid").on("mouseup",function(e){
    return false;
});

Hope this helps ...

like image 21
saraf Avatar answered Sep 28 '22 08:09

saraf