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?
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.
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();
<input onClick="this.select()" value="Blabla und Blublu" type="text" />
Should work
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 trigger
ing 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.
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With