I have the same problem as the user in this question, which is due to this bug in Webkit. However, the workaround provided will not work for my app. Let me re-state the problem so that you don't have to go read another question:
I am trying to select all the text in a textarea when it gets focus. The following jQuery code works in IE/FF/Opera:
$('#out').focus(function(){ $('#out').select(); });
However, in Chrome/Safari the text is selected--very briefly--but then the mouseUp event is fired and the text is deselected. The following workaround is offered in the above links:
$('#out').mouseup(function(e){ e.preventDefault(); });
However, this workaround is no good for me. I want to select all text only when the user gives the textarea focus. He must then be able to select only part of the text if he chooses. Can anyone think of a workaround that still meets this requirement?
How about this?
$('#out').focus(function () { $('#out').select().mouseup(function (e) { e.preventDefault(); $(this).unbind("mouseup"); }); });
The accepted answer (and basically every other solution I found so far) does not work with keyboard focus, i. e. pressing tab, at least not in my Chromium 21. I use the following snippet instead:
$('#out').focus(function () { $(this).select().one('mouseup', function (e) { $(this).off('keyup'); e.preventDefault(); }).one('keyup', function () { $(this).select().off('mouseup'); }); });
e.preventDefault()
in the keyup
or focus
handler does not help, so the unselecting after a keyboard focus seems to not happen in their default handlers, but rather somewhere between the focus
and keyup
events.
As suggested by @BarelyFitz, it might be better to work with namespaced events in order to not accidentally unbind other event handlers. Replace 'keyup'
with 'keyup.selectText'
and 'mouseup'
with 'mouseup.selectText'
for that.
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