2

I have a script where i can just click on a div and add information to a textarea. This is working, however the cursor is always at the start of the information that I inserted.

<div id="click">Click to insert</div>
<textarea id="info">I want to</textarea>

here is the jquery:

<script>
    $(document).ready(function(){
        $('#click').on('click',function(){
            var i=$('#info').val();
            var n="Insert this";//information to be inserted
            $('#info').val(i + n).focus();
        });
    });
</script>

Now the entire thing should read I want to insert this followed by the cursor. Instead the cursor is in the middle like this I want to [cursor] insert this. Is there any way that I can have the cursor focus at the end of the contents in the fields?

Bryan
  • 258
  • 2
  • 12
  • This may help: http://stackoverflow.com/questions/4609405/set-focus-after-last-character-in-text-box – James Donnelly Feb 13 '13 at 14:55
  • Still not working. focus is still before the inserted text. – Bryan Feb 13 '13 at 15:01
  • Did you try with the full SetCaretAtEnd function from the accepted answer? If so, you can try this: http://stackoverflow.com/questions/13425363/jquery-set-textarea-cursor-to-end-of-text Edit: If the element already has focus you may need to call `.blur()` beforehand. – James Donnelly Feb 13 '13 at 15:03
  • 2
    You should probably start by replacing `$('click')` with `$('#click')` ! That's an error !!!! – adeneo Feb 13 '13 at 15:03
  • See this post [jQuery Set Cursor Position in Text Area](http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area) – Dumitru Chirutac Feb 13 '13 at 15:04

2 Answers2

3

Try out this one JSFiddle http://jsfiddle.net/adiioo7/2D9Td/ :-

$(document).ready(function () {
    $('#click').on('click', function () {
        var i = $('#info').val();
        var n = "Insert this"; //information to be inserted
        $('#info').focus().val(i + n);
    });
});

Just changed the sequence of focus and val in last js call.

Aditya Singh
  • 9,512
  • 5
  • 32
  • 55
0

How about a jQuery plugin ?

$.fn.setCaretToEnd = function () {
    return this.each(function () {
        if (this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(this.value.length, this.value.length);
        } else if (this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', this.value.length);
            range.moveStart('character', this.value.length);
            range.select();
        }
    });
};

$(document).ready(function () {
    $('#click').on('click', function () {
        var i = $('#info').val();
        var n = "Insert this";

        $('#info').val(i + n).focus().setCaretToEnd();
    });
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388