0

How do I input a character, with either JQuery or plain JavaScript, as if it had been typed?

I have a contenteditable section, and am intercepting user input in order to replace certain characters (for example straight quotes with curly ones). I have the following JQuery to intercept a character, but am not sure of the best way to input the new character.

$('.editor').keypress(function(e) {
    console.log(e.which);
    if (e.which === 39) {
        e.preventDefault();
        // replace with curly quotes
    }
});
tsvallender
  • 2,615
  • 6
  • 32
  • 42
  • are you looking for something like this: http://stackoverflow.com/questions/3661415/replacing-characters-using-jquery – 97ldave Apr 30 '13 at 17:31

2 Answers2

3

What about document.execCommand:

$('.editor').keypress(function(e) {
  console.log(e.which);
  if (e.which === 39) {
    e.preventDefault();
    document.execCommand('insertHTML', false, 'String To Insert');
  }
});

insertHTML doesn't work in IE so use:

document.selection.createRange().pasteHTML('html to insert');

A list of commands and examples can be found at: https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla


P.S. I think e.which will report 0 in certain browsers so do something like:

var code = e.keyCode || e.which;
Alex
  • 76
  • 2
0

You can do

$('.editor').keypress(function(e) {
    console.log(e.which);
    if (e.which === 39) {
        e.preventDefault();
        $(this).text(function(index, text){
            return text.replace(/"/gi, '-'); // <--Change this to replace the " with what you need.
        });
    }
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • I think I confused matters by talking about replacements, I basically just need to know how to input a character at the caret programatically. There is no character to replace in the element, as I have intercepted it. – tsvallender Apr 30 '13 at 18:08
  • Ahh I see. This might help: http://stackoverflow.com/questions/1064089/inserting-a-text-where-cursor-is-using-javascript-jquery – tymeJV Apr 30 '13 at 18:13
  • Having problems with most of those approaches which are, I think, down to dealing with contenteditable, not a traditional text input of some variety. – tsvallender Apr 30 '13 at 18:52
  • Ahh, well, this question deals with that specifically: http://stackoverflow.com/questions/6690752/insert-html-at-cursor-in-a-contenteditable-div – tymeJV Apr 30 '13 at 19:52