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.

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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/

3 Comments

tnx that was great, but the timeout seems as a code smell, so I went with willcwf's answer
@NirSmadar his code doesn't work for me on Chrome for Android.
@rybo1114 tnx, i dont need mobile support
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();
});

3 Comments

He already has that code. elm will be the element he has selected in a previous line.
OK? You haven't contributed anything to the code in the first post.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.