Reputation: 457
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.
Upvotes: 2
Views: 2149
Reputation: 722
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
Upvotes: 2
Reputation: 1000
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();
});
Upvotes: 0
Reputation: 12588
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/
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/
Upvotes: 1