How do I insert a character at the caret with javascript?

前端 未结 6 959
-上瘾入骨i
-上瘾入骨i 2021-01-02 05:55

I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?

The script needs to find the active textbo

6条回答
  •  -上瘾入骨i
    2021-01-02 06:39

    I think Jason Cohen is incorrect. The caret position is preserved when focus is lost.

    [Edit: Added code for FireFox that I didn't have originally.]

    [Edit: Added code to determine the most recent active text box.]

    First, you can use each text box's onBlur event to set a variable to "this" so you always know the most recent active text box.

    Then, there's an IE way to get the cursor position that also works in Opera, and an easier way in Firefox.

    In IE the basic concept is to use the document.selection object and put some text into the selection. Then, using indexOf, you can get the position of the text you added.

    In FireFox, there's a method called selectionStart that will give you the cursor position.

    Once you have the cursor position, you overwrite the whole text.value with

    text before the cursor position + the text you want to insert + the text after the cursor position

    Here is an example with separate links for IE and FireFox. You can use you favorite browser detection method to figure out which code to run.

    
    
    
    
    
    
    Insert IE
    Insert FF

    This will also work with textareas. I don't know how to reposition the cursor so it stays at the insertion point.

提交回复
热议问题