I can't work out why I can't get the the content of a textarea to be selected when the textarea receives focus.
Please visit a live example here: http://jsfiddle.net/mikkelbreum/aSvst/1
Using jQuery, this is my code. (IN SAFARI) It makes the text selected in case of the click event, but not the focus event:
$('textarea.automarkup')
.mouseup(function(e){
// fixes safari/chrome problem
e.preventDefault();
})
.focus(function(e){
$(this).select();
})
.click(function(e){
$(this).select();
});
Select Input Text in a Text Input with Reacttarget. 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.
The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
Focus a Textarea or Text FieldWhen a text field is active it is said to be focused. Setting the focus means making the field active so the cursor is blinking and ready to accept text input. This method can also be used to make a text field active when something else happens (see below).
The simplest thing to do is to combine your existing code with a timer, since the focus
event is generally too early in WebKit:
jsFiddle example: http://jsfiddle.net/NWaav/2/
Code:
$('textarea.automarkup').focus(function() {
var $this = $(this);
$this.select();
window.setTimeout(function() {
$this.select();
}, 1);
// Work around WebKit's little problem
function mouseUpHandler() {
// Prevent further mouseup intervention
$this.off("mouseup", mouseUpHandler);
return false;
}
$this.mouseup(mouseUpHandler);
});
Tim Down's answer got me close, but it still didn't work when clicking & dragging in Chrome, so I did this (Coffeescript).
$.fn.extend
copyableInput: ->
@.each ->
$input = $(this)
# Prevent the input from being edited (but allow it to be selected)
$input.attr 'readonly', "readonly"
if $input.is 'textarea'
$input.unbind('focus').focus ->
input = $(this).select()
$input.data 'selected', true
setTimeout ->
input.select()
, 0
# Work around WebKit's little problem
$input.bind 'mousedown mouseup', (e) ->
$input.select()
if $input.data('selected') == true
e.preventDefault()
return false
$input.unbind('blur').blur ->
$input.data 'selected', false
else
# Select all the text when focused (I'm intentionally using click for inputs: http://stackoverflow.com/questions/3150275/jquery-input-select-all-on-focus)
$input.unbind('click').click ->
input = $(this).select();
setTimeout ->
input.select()
, 0
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