Limit a field in the WordPress visual editor when sending a post

1

I am using a plugin called USP PRO to send content from a form, however I am presented with the following problem:

I have a

asked by pio 08.02.2016 в 07:36
source

1 answer

2

With TinyMCE you can add event handlers when you start the editor using the setup parameter. So in your initialization of TinyMCE, you should do something like this:

tinymce.init({ 
    selector:'.usp-input-content',
    setup: function(editor) {
        editor.on("keyup", function() {

            // el código que quieres para el evento keyup

        });
    }
});

You could copy and paste your code for the event keyup and put it inside the function that controls it for the editor. The only thing that you would have to change is $(this).val() that would no longer work, and instead use tinymce.activeEditor.getContent() that will return the content of the active TinyMCE editor.

Thus the code would be as follows:

tinymce.init({ 
    selector:'.usp-input-content',
    setup: function(editor) {
        editor.on("keyup", function() {
            var limit = 500; // word limit
            var count = tinymce.activeEditor.getContent().split(/\b[\s,\.-:;]*/).length;
            $('.counter').html(count);
            if (count > limit) {
                alert('Recuerda : Tu texto debe tener máximo 500 palabras!');
                return false;
            }
        });
    }
});

If you have no control over when TinyMCE editors are initialized and therefore can not add setup with event handlers, you can wait for the page to load and, once initialized the TinyMCE editors, add the events.

The part of " once the TinyMCE editors are initialized " is essential in this case. So to make sure that they have been initialized, we will execute the following code at the end of the page using setTimeout to allow time for TinyMCE to start the editors:

// 100ms después de que se cargue la página (puede que necesites ajustar este valor)
setTimeout(function() {

    // comprueba todos los editores de TinyMCE
    for (var x = 0; x < tinymce.editors.length; x++) {

        // si tienen la clase que quieres
        if (tinymce.editors[x].targetElm.className == "usp-input-content") {

            // añade el evento onkeyup con tu código
            tinymce.editors[x].on("keyup", function(editor, e) {
                var limit = 500; // word limit
                var count = tinymce.activeEditor.getContent().split(/\b[\s,\.-:;]*/).length;
                $('.counter').html(count);
                if (count > limit) {
                    alert('Recuerda : Tu texto debe tener máximo 500 palabras!');
                    return false;
                }
            });
        }
    }
}, 100);
    
answered by 08.02.2016 в 14:31