How can I make it so when you click inside a textarea, its entire content gets selected?
And eventually when you click again, to deselect it.
This question is related to
javascript
jquery
forms
textarea
selection
I ended up using this:
$('.selectAll').toggle(function() {
$(this).select();
}, function() {
$(this).unselect();
});
Selecting text in an element (akin to highlighting with your mouse)
:)
Using the accepted answer on that post, you can call the function like this:
$(function() {
$('#textareaId').click(function() {
SelectText('#textareaId');
});
});
$('textarea').focus(function() {
this.select();
}).mouseup(function() {
return false;
});
Better way, with solution to tab and chrome problem and new jquery way
$("#element").on("focus keyup", function(e){
var keycode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if(keycode === 9 || !keycode){
// Hacemos select
var $this = $(this);
$this.select();
// Para Chrome's que da problema
$this.on("mouseup", function() {
// Unbindeamos el mouseup
$this.off("mouseup");
return false;
});
}
});
Slightly shorter jQuery version:
$('your-element').focus(function(e) {
e.target.select();
jQuery(e.target).one('mouseup', function(e) {
e.preventDefault();
});
});
It handles the Chrome corner case correctly. See http://jsfiddle.net/Ztyx/XMkwm/ for an example.
Source: Stackoverflow.com