Question

I've been trying to insert text into the TinyMCE Editor at the focused paragraph element (<p>) exactly where the cursor is but got no luck!!

var elem = tinyMCE.activeEditor.dom.get('tinymce');
var child = elem.firstChild;
while (child) {
    if (child.focused) {
        $(child).insertAtCaret("some text");
    }
    child = child.nextSibling;
}

If anyone has any idea on how to solve this I'll be very thankful.

Était-ce utile?

La solution

You should use the command mceInsertContent. See the TinyMCE documentation.

tinymce.activeEditor.execCommand('mceInsertContent', false, "some text");

Autres conseils

The above answer is good, but it is worth pointing out that this can be used to insert any HTML.

For example:

tinymce.activeEditor.execCommand('mceInsertContent', false, " <b>bolded text</b> ");

will insert bolded text at the current cursor location.

Some other interesting observations:

mceInsertRawHTML also works, but tends to put the cursor at the beginning of the current line in my version of tinyMCE, but ymmv.

mceReplaceContent works as well, but in my case did not work well when the cursor was at the end of the current content.

Again, see the documentation for more information.

If using popup window, you may use:

tinyMCEPopup.editor.execCommand('mceInsertLink', false, 'some content goes here');

// mceInsertLink inserts the content at the current cursor or caret position. // If the editor is not on focus, the insertion will be at the very first line content in the editor.

If you want to insert HTML tags and javascript variables, you may use, for example:

<script type='text/javascript'>

    var my_var= "some value";
    var my_var_two = 99;

    tinyMCEPopup.editor.execCommand('mceInsertLink', false, 
                    '<span >[' + my_var + ', ' + my_var_two + ']</span>');       
    tinyMCEPopup.close(); // too close the popup window

</script>

If you are in a PHP file, you may use the same strategy, just use PHP instead of JavaScript, for example:

<script type='text/javascript'>
    tinyMCEPopup.editor.execCommand('mceInsertContent', false, 
               '<span >[' + <?php echo $my_php_var; ?> +']</span>'); 
</script>

You can also assign PHP variables (assuming you are in .php file) to Javascript variables and use them in the editor content insertion, for example:

<script type='text/javascript'>

    var my_var= "<?php echo $my_php_var; ?>";
    var my_var_two = "<?php echo $my_php_var_two_or_a_function_call; ?>";

    tinyMCEPopup.editor.execCommand('mceInsertLink', false, 
                     '<span >[' + my_var + ', ' + my_var_two + ']</span>');       
    tinyMCEPopup.close(); // too close the popup window

</script>

I want to add one more thing here if you have more than one editor on your page than you can also do it like this.

tinyMCE.get('idOfEditor').execCommand('mceInsertContent', true, 'your text goes here')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top