Bluefire
Bluefire

Reputation: 14099

JQuery - placing the cursor at the end of a textarea when it is focused on

First, some of you may notice that I reposted this question after deleting it. This is because it was mistakenly marked as a duplicate by someone who didn't bother to check - the question he linked to was about an <input> element; that solution does not work for textareas.

Anyway, consider the following code:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function caek() {
    $('textarea[name=txt1]').val("cake");
    $('textarea[name=txt1]').focus();
}
</script>
</head>
<body>
<div id="bar"></div>
<form name="frm1" id="cake">
<textarea name="txt1"></textarea>
</form>
<input type="button" value="Activate"
onclick="caek()">
</body>
</html>

When you run that, you will notice that the cursor is pushed to the start of the textarea, before the text. How can I make it come after all the text, at the end of the textarea? A non-inline solution would be optimal, but anything will do.

And a standalone solution (no plugins etc) would be perfect.

Upvotes: 1

Views: 642

Answers (3)

elclanrs
elclanrs

Reputation: 94101

This works.

$ta.text($ta.text()).focus()

Demo: http://jsfiddle.net/elclanrs/WWsBa/

Upvotes: 2

septemberbrain
septemberbrain

Reputation: 1008

This is working for me.

function caek() {
    txtArea = $('textarea[name=txt1]');
    txtArea.val("cake");
    txtArea.focus();    
    tmpStr = txtArea.val();
    txtArea.val('');
    txtArea.val(tmpStr);
}

Upvotes: 2

tangentstorm
tangentstorm

Reputation: 7295

You can use the rangyinputs jQuery plugin to do this in a cross platform way.

There's a demo here:

http://rangyinputs.googlecode.com/svn/trunk/demos/textinputs_jquery.html

Set the start and end to the same number and it'll set the cursor to that point (though it doesn't focus the textarea, so you have to tab into it to see the effect). In your case, you'd want to set it to the length of the text.

Upvotes: 1

Related Questions