TinyMCE, 2 times to Validate Even When Textbox Not Empty

456 Views Asked by At

Using TINYMce and validation, but it takes to two times to post and it doesn't matter whether the textarea is empty or not. I research this but wasn't able to find anything that worked. Below is code snippets.

Model

[Required(ErrorMessage = "*Response Required")]
[UIHint("tinymce_jquery_full"), AllowHtml]
public string LibrarianResponse { get; set; }

View

<span style="color: red;font-weight: 700;">@Html.ValidationMessageFor(m => m.LibrarianResponse)</span>
    <div class="editor-field">
        @Html.EditorFor(model => model.LibrarianResponse)
    </div> 

<script type="text/javascript">
            jQuery(function ($) {
            $('#submit').click(function () {
            tinyMCE.triggerSave();});
            });
</script>

 <input type="submit" value="Submit" />

Thank in advance.

3

There are 3 best solutions below

2
On

It takes a small amount of time for TinyMCE to update the original (now hidden) inputs it operates on top of. You are doing that with triggerSave. However, the form submit is likely going to continue and run before triggerSave finishes. So do this:

jQuery(function ($) {
    $('#submit').click(function(evt) {
        evt.preventDefault();
        tinyMCE.triggerSave();
        $(evt.target).closest('form').submit();
    });
});
1
On

I solved this problem by having tinyMCE update the underlying textarea anytime the tinyMCE textarea changes:

function tinyChanged(inst) {
    if (inst.isDirty()) {
        inst.save();
    }
}

tinymce.init({
    selector: "myTextArea",
    setup: function(ed) {
        ed.on("change", function () {
            tinyChanged(ed);
        })
    }
});
1
On

Okay Finally resolved this issue. My original code was nearly correct.

You'll notice that in my original question I have the following code:

<script type="text/javascript">
            jQuery(function ($) {
            $('#submit').click(function () {
            tinyMCE.triggerSave();});
            });
</script>

Also, I have this below for my textarea:

<span style="color: red;font-weight: 700;">
  @Html.ValidationMessageFor(m => m.LibrarianResponse)
</span>
<div class="editor-field">
  @Html.EditorFor(model => model.LibrarianResponse)
</div> 

All I had to do was put LibrarianResponse (which was the id of the textarea in Google Chrome - spotted using dev tools) into the .triggerSave function.

So this worked. See below:

 jQuery(document).ready(function ($) {
                    $('#submit').click(function () {
                        tinyMCE.triggerSave('#LibrarianResponse');

                    });
                });

Thanks to those who responded to my question. I appreciate it.