2

There's a lot of solution around here

to place cursor at the end of text for input or textbox tag.

Use JavaScript to place cursor at end of text in text input element

jQuery Textbox Cursor to end of Text?

jQuery Set Cursor Position in Text Area

Currently, I use div tag with contenteditable = "true" instead of using input or textbox tag.

Unfortunately, even I replace val to text to make the code work, none of them works as intended.

Any thought? Thanks.

Community
  • 1
  • 1
  • 1
    Seems all of the referenced posts answer your question? – PW Kad Feb 10 '14 at 02:56
  • They related, and they works only for `input` or `textbox` tag not for `div` tag with `contenteditable = "true"` –  Feb 10 '14 at 03:18

2 Answers2

1

I've found a similar question, and this seems unbelievably complicated.

Set cursor position on contentEditable <div>

Although someone claims something, I used, Zane Claes's answer, and works as intended.

$.fn.focusEnd = function() {
    $(this).focus();
    var tmp = $('<span />').appendTo($(this)),
        node = tmp.get(0),
        range = null,
        sel = null;

    if (document.selection) {
        range = document.body.createTextRange();
        range.moveToElementText(node);
        range.select();
    } else if (window.getSelection) {
        range = document.createRange();
        range.selectNode(node);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    tmp.remove();
    return this;
}
Community
  • 1
  • 1
0

After all solutions from above question, I gave one solution. Enter the text and press enter the cursor move to end of text,

JsFiddle

Try with,

$("div").keypress(function (event) {

    if (event.which == '13') {

        var val = $(this).text();    

        $(this).text('');
        $(this).text(val);
        setCursorToEnd($(this).get(0))

        event.preventDefault();
    }
});
function setCursorToEnd(ele)
  {

    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
  }
dhana
  • 6,487
  • 4
  • 40
  • 63
  • Thanks, in fact, I've tried this code prior to this question, and had an error `Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist` for `range`. –  Feb 10 '14 at 03:23
  • In fact, yes, and haven't seen it focused or cursror location. –  Feb 10 '14 at 03:32
  • Are you pressed the enter buttion ?. You need to press enter button. – dhana Feb 10 '14 at 03:41
  • Anyway, this code does not work for my project. I will post alternative answer by myself now. –  Feb 10 '14 at 03:44