简体   繁体   中英

Insert text at caret position IE 8

I want to be able to enter some text at the caret position. Currently I can insert text at the end or start of the textbox OR replace the whole textbox content with the new text. How can I get the new text to insert into the textbox at the caret position?

What I want: ie textbox contatins "12,3" with caret being where the coma is. After function call it ends up like so: "12new text3"

Current code:

var sel = document.getElementById("txtbox");
var text = "new text";

//ie 8
if (document.selection) {
 var range = document.selection.createRange();

   sel.focus();
   range = sel.createTextRange();
   range.collapse(false);
   range.text = text;
   range.select();
}

I've not IE8 to test, but try this:

if (document.selection) {
    var range = document.selection.createRange();
    range.text = text;
    range.select();
}

In your code you've defined range twice, and then collapsed the range (containing all the text in a textbox) to the end of the text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM