cross browser - Inserting text at cursor in a textarea, with Javascript - Stack Overflow

I've had a look round the web for solutions, and there are some, but they all seem to split code i

I've had a look round the web for solutions, and there are some, but they all seem to split code into supporting IE and Firefox.

I was wondering if there's a more elegant way which would work on every browser, to insert some text at the cursor in a textarea.

Thanks very much.

I've had a look round the web for solutions, and there are some, but they all seem to split code into supporting IE and Firefox.

I was wondering if there's a more elegant way which would work on every browser, to insert some text at the cursor in a textarea.

Thanks very much.

Share Improve this question edited Dec 28, 2021 at 17:09 General Grievance 4,98838 gold badges37 silver badges55 bronze badges asked Jul 22, 2010 at 11:26 richw81richw81 611 gold badge1 silver badge2 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 21

No, there isn't. IE has its TextRange objects to do the job. IE >= 9 and everything else for the last long time has selectionStart and selectionEnd properties on textareas and text inputs. This particular task isn't too bad: the following will delete the current selection (if one exists), insert text at the caret and reposition the caret immediately after the inserted text, in all the major browsers:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}

implement both: the code that is supporting FF and the Code supporing the IE. You can use Frameworks to write Code for both browsers. Than the Framework will do the work of splitting the differences between the browsers.

It's sad, but browsers aren't 100% compatible!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1739130607a4101605.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信