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

Question :

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

Answer :

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 textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.

EDIT: It is also ok to insert the character “last” in the previously active textbox.


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

Read More  What is the best way to iterate through an array in Classic Asp VBScript?

[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.

Read More  SharePoint WSS 3.0 Integration with Mac OSX (either Safari or Firefox)

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.

That’s the answer How do I insert a character at the caret with javascript?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you