Problems with [contenteditable] elements and jQuer

2019-07-26 11:15发布

I prepared a DEMO which demonstrates [contenteditable] element has no HTML form. As for me, it's a problem, because jQuery validation plugin need form. Look at the source code snippet from here starting from 383 line:

function delegate( event ) {
    var validator = $.data( this.form, "validator" ),
        eventType = "on" + event.type.replace( /^validate/, "" ),
        settings = validator.settings;
    if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) {
        settings[ eventType ].call( validator, this, event );
    }
}

$( this.currentForm )
    .on( "focusin.validate focusout.validate keyup.validate",
        ":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " +
        "[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " +
        "[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " +
        "[type='radio'], [type='checkbox'], [contenteditable]", delegate )

    // Support: Chrome, oldIE
    // "select" is provided as event.target when clicking a option
    .on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate );

Here we can see, elements, one of which is a [contenteditable] listen to events and then call delegate event handler.

When [contenteditable] trigger some event from this list, delegate method try to get validator from element var validator = $.data( this.form, "validator" ) but as I said earlier [contenteditable] has no form (see DEMO).

Is there any way to solve this problem? May be it's possible to add form to all [contenteditable] elements?

2条回答
女痞
2楼-- · 2019-07-26 11:48

does exploring the ignore option of validate solve your problem?

ignore: ":hidden:not('#summernote')"

Updated fiddle - https://jsfiddle.net/z6eLvk0b/2/

查看更多
▲ chillily
3楼-- · 2019-07-26 12:07

This is a known bug in jquery validator plugin. However, this has been fixed now in this pull request, and should be released soon.

Fix 1:

If you cannot wait for a release, the fix is to put this code at the start of delegate() method. The solution has been made by @svrx.

// Set form expando on contenteditable
if ( !this.form && this.hasAttribute( "contenteditable" ) ) {
    this.form = $( this ).closest( "form" )[ 0 ];
}

As you can see the fix is simply to set the form to the parent element.

Fix 2:

As @chrisAtomix said in his comments, don't use the latest jquery validator plugin. Instead use a lower version where contenteditable feature has not been added. He is using v1.14.0.

查看更多
登录 后发表回答