How to make textarea filed mandatory when I've applied TinyMCE
Asked Answered
C

2

5

I want to make textarea filed mandatory when I've applied TinyMCE.

If I add required attribute to <textarea>, it causes that I cannot submit the form even if I fill in the form!

How can I solve this problem?

tinymce.init({
    selector: '#summaryId',
    max_chars: 255, // max. allowed chars
    plugins: "paste",
    setup: function (ed) {
        var allowedKeys = [8, 37, 38, 39, 40, 46]; // backspace, delete and cursor keys
        ed.on('keydown', function (e) {
            if (allowedKeys.indexOf(e.keyCode) != -1) return true;
            if (tinymce_getContentLength() + 1 > this.settings.max_chars) {
                e.preventDefault();
                e.stopPropagation();
                return false;
            }
            return true;
        });
        ed.on('keyup', function (e) {
            tinymce_updateCharCounter(this, tinymce_getContentLength());
        });
    },
    init_instance_callback: function () { // initialize counter div
        $('#' + this.id).prev().append('<div class="char_count" style="text-align:left; color:grey;"></div>');
        tinymce_updateCharCounter(this, tinymce_getContentLength());
    },
    paste_preprocess: function (plugin, args) {
        var editor = tinymce.get(tinymce.activeEditor.id);
        var len = editor.contentDocument.body.innerHTML.length;
        var textLen = args.content.length;// $(args.content).text();
        if (len + textLen > editor.settings.max_chars) {
            alert('Pasting this exceeds the maximum allowed number of ' + editor.settings.max_chars + ' characters.');
            args.content = '';
        } else {
            //tinymce_updateCharCounter(editor, len + text.length);
        }
    }
});

in cshtml file:

<textarea asp-for="Article.Summary" class="form-control" id="summaryId" maxlength="255"></textarea>
Chaeta answered 24/3, 2020 at 15:25 Comment(0)
M
8

There are two issues you will have to address here...

1 - The required attribute on the <textarea>

When you invoke TinyMCE the original <textarea> you have on the page is hidden and TinyMCE places a chunk of HTML onto the page. The editing rectangle is an <iframe> and the menus/toolbars are HTML that surrounds that <iframe>.

Because the original <textarea> is now hidden, making it required is an issue and the browser will complain that you have a hidden form element marked as required.

Bottom line for this first issue is you can't mark a hidden <textarea> as required.

2 - TinyMCE and the <textarea>

TinyMCE does not keep the underlying <textarea> in sync at all times - for most use cases this would add unneeded overhead to the page while someone is creating content.

If you are using a standard HTML form post, when you post the form, TinyMCE will update the <textarea> before the form is posted. Unfortunately, most modern frameworks don't use a standard HTML form post but instead do something using JavaScript/AJAX. You can use the following API call to force TinyMCE to update the <textarea>:

tinymce.triggerSave();

This will force TinyMCE to update the <textarea> when it is called. You can either:

  • Do this in the onsubmit event of the form
  • Do this in the TinyMCE init:

    tinymce.init({
        selector: "textarea",
        setup: function (editor) {
            editor.on('change', function () {
                tinymce.triggerSave();
            });
        }
    });
    
Moonstone answered 24/3, 2020 at 15:52 Comment(3)
It's work! Now, I want to show a proper message to user, if they didn't fill the field. How can I do it?Chaeta
You can add a red border to the editor simply by CSS: form.was-validated { textarea.form-control:invalid + div.tox { border: 1px solid #dc3545; } }Mcgraw
If you are on old version of TinyMCE, you can use editor.onChange.add(function(){});, instead of editor.on('change',function(){});.Furgeson
G
4

One more hack - to inform users that the field is required if they leave it empty. We have to unhidden our textarea. So after Fromin code we add:

init_instance_callback : function(editor) {
        let editorH = editor.editorContainer.offsetHeight;
        $('#formTranslation_trad')
            .css({
                'position':'absolute',
                'height':editorH
            })
            .show();
    },

So: we take height of editor and set this to our textarea (probably we have to do the same on change textarea size?).

We have to set position absolute to avoid design problems and next add width and margins for hide textearea after editor.

When we send empty field there will be tooltip with warning and border on red (or other color depends of system settings).

Gingrich answered 3/2, 2021 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.