2

How do I achieve the following behavior in an html text input: when a user clicks the input, all the text will be selected, even if it's already selected. Thus there won't be any possibility to delete/select certain characters.

currently I have the following:

elm.on('click', function(e) {
    e.preventDefault();
    $(this).select();
});

but if the text is selected then a click displays a carret.

Nir Smadar
  • 357
  • 2
  • 5
  • 15

3 Answers3

2

This was a fun one!

The trick is not to preventDefault() on the click event, but instead the mouseDown event.

$('#clickme').on('mousedown', function(e) {
  e = e || window.event;
  e.preventDefault();
  $(this).select();
});

Here's a working fiddle and the related question I got the answer from

willcwf
  • 712
  • 7
  • 10
  • Have you tried this on a mobile device? To select it in Chrome for Android, you have to tap the input, then tap away from the input, then tap it again. – rybo111 Jan 21 '16 at 09:11
1

Thus there won't be any possibility to delete/select certain characters.

For this, I recommend using readonly on your input:

<input readonly type="text" ...

Also, if you remove e.preventDefault() it will continue to stay selected.

See this fiddle: https://jsfiddle.net/dgryhdtL/

Update

Sometimes when you click selected text, it will de-select. To get around that, you need to create a small delay:

var that = $(this);
setTimeout(function(){
  that.select();
}, 100);

See this fiddle: https://jsfiddle.net/dgryhdtL/1/

rybo111
  • 12,240
  • 4
  • 61
  • 70
0

Here is simple code:

$("input[type='text']").on("click", function () {
    //select the text in text field
    $(this).select();
});

Edit: If you have your element already in elm variable than you do not need to write jQuery selector. You can use:

elm.on("click", function () {
    //select the text in text field
    $(this).select();
});
Kamal Singh
  • 990
  • 8
  • 13
  • He already has that code. `elm` will be the element he has selected in a previous line. – rybo111 Jan 20 '16 at 16:23
  • OK? You haven't contributed anything to the code in the first post. – rybo111 Jan 20 '16 at 16:42
  • Your answer and subsequent edits make no attempt to answer the question. Read the question. It has nothing to do with how to select the element. – rybo111 Jan 20 '16 at 17:00