繁体   English   中英

如果联系表单7在AJAX提交中返回无效字段,则运行自定义函数

[英]Running a custom function if Contact Form 7 returns an invalid field on AJAX submit

我使用的是WordPress插件Contact Form 7 ,如果特定字段上有错误,我需要处理一些数据,不确定是否可以使用钩子或其他方法来完成,因为我需要运行一些JavaScript代码而不是PHP,因此,我假设用户尝试提交表单时需要附加onclick事件?

如果可以用一个钩子好歹做我相信它会与完成这一个

如果可以用钩子完成,实现此目的的最佳方法是什么? 如果没有,我想将一个onclick事件附加到按钮将很容易,但是我不确定如何仅在存在验证错误且CF7 JS代码已经运行之后才能使其运行?

表单的HTML:

<div role="form" class="wpcf7" id="wpcf7-f1304-p10-o1" lang="en-US" dir="ltr">
    <div class="screen-reader-response"></div>
    <form name="" action="/freetrademarksearch/#wpcf7-f1304-p10-o1" method="post" class="wpcf7-form" enctype="multipart/form-data" novalidate="novalidate">
        <div style="display: none;">
            <input type="hidden" name="_wpcf7" value="1304" />
            <input type="hidden" name="_wpcf7_version" value="4.1.2" />
            <input type="hidden" name="_wpcf7_locale" value="en_US" />
            <input type="hidden" name="_wpcf7_unit_tag" value="wpcf7-f1304-p10-o1" />
            <input type="hidden" name="_wpnonce" value="a2009d4694" />
        </div>
        <div class="field_wrapper">
            <p class="title">Trademark to be searched</p>
            <div class="field">
                <span class="wpcf7-form-control-wrap trademark"><input type="text" name="trademark" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required form-control" aria-required="true" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Upload Logo <span class="optional">(optional)</span></p>
            <div class="field">
                <div class="btn browse_btn">
                    <span class="wpcf7-form-control-wrap logo"><input type="file" name="logo" value="1" size="40" class="wpcf7-form-control wpcf7-file" aria-invalid="false" /></span>
                </div>
                <div class="wp_is_annoying">
                    <span id="upload_filename" class="file_chosen">No file selected</span>
                </div>
                </p>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Goods/Services the trademark is, or will be, used to identify</p>
            <div class="field">
                <span class="wpcf7-form-control-wrap identify"><input type="text" name="identify" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required form-control" aria-required="true" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">If you already promote this in Australia, what was the first date of promotion?</p>
            <div class="field">
                <span class="wpcf7-form-control-wrap date-promoted"><input type="text" name="date-promoted" value="" size="40" class="wpcf7-form-control wpcf7-text form-control" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Has promotion been continuous since the above date?</p>
            <div class="field radio_btns">
                <div class="holder">
                    <span class="wpcf7-form-control-wrap continuous_promotion"><span class="wpcf7-form-control wpcf7-radio" id="yes_continuous_promotion"><span class="wpcf7-list-item first last"><label><input type="radio" name="continuous_promotion" value="Yes" />&nbsp;<span class="wpcf7-list-item-label">Yes</span></label></span></span></span>
                </div>
                <div class="holder">
                    <span class="wpcf7-form-control-wrap continuous_promotion"><span class="wpcf7-form-control wpcf7-radio" id="no_continuous_promotion"><span class="wpcf7-list-item first last"><label><input type="radio" name="continuous_promotion" value="No" />&nbsp;<span class="wpcf7-list-item-label">No</span></label></span></span></span>
                </div>
                </p>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Full Name</p>
            <div class="field half">
                <span class="wpcf7-form-control-wrap first-name"><input type="text" name="first-name" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-validates-as-required first form-control" aria-required="true" aria-invalid="false" placeholder="First Name" /></span><span class="wpcf7-form-control-wrap last-name"><input type="text" name="last-name" value="" size="40" class="wpcf7-form-control wpcf7-text form-control" aria-invalid="false" placeholder="Last Name" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Email Address:</p>
            <div class="field">
                <span class="wpcf7-form-control-wrap email"><input type="email" name="email" value="" size="40" class="wpcf7-form-control wpcf7-text wpcf7-email wpcf7-validates-as-required wpcf7-validates-as-email form-control" aria-required="true" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Phone Number:</p>
            <div class="field">
                <span class="wpcf7-form-control-wrap phone"><input type="text" name="phone" value="" size="40" class="wpcf7-form-control wpcf7-text form-control" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">Comment: <span class="optional">(optional)</span></p>
            <div class="field">
                <span class="wpcf7-form-control-wrap comments"><textarea name="comments" cols="40" rows="10" class="wpcf7-form-control wpcf7-textarea form-control" aria-invalid="false"></textarea></span><br />
                <span class="wpcf7-form-control-wrap hello-wrap" style="display:none !important;visibility:hidden !important;"><input class="wpcf7-form-control wpcf7-text"  type="text" name="hello" value="" size="40" tabindex="-1" /><br><small>Please leave this field empty.</small></span>
            </div>
        </div>
        <div class="field_wrapper">
            <p class="title">How did you find us? <span class="optional">(optional)</span></p>
            <div class="field">
                <span class="wpcf7-form-control-wrap find-us"><input type="text" name="find-us" value="" size="40" class="wpcf7-form-control wpcf7-text form-control" aria-invalid="false" /></span>
            </div>
        </div>
        <div class="field_wrapper subscribe">
            <div class="field">
                <div class="td">
                    <span class="wpcf7-form-control-wrap newsletter"><span class="wpcf7-form-control wpcf7-checkbox" id="newsletter"><span class="wpcf7-list-item first last"><input type="checkbox" name="newsletter[]" value="yes" />&nbsp;<span class="wpcf7-list-item-label">yes</span></span></span></span>
                </div>
                <div class="td">
                    <label for="newsletter">I would like to receive newsletters from time to time.</label>
                </div>
                </p>
            </div>
        </div>
        <div class="field_wrapper submit">
            <div class="field">
                <input type="submit" value="Send" class="wpcf7-form-control wpcf7-submit btn" />
            </div>
        </div>
        <div class="wpcf7-response-output wpcf7-display-none"></div>
    </form>
</div>

可能最简单的方法是在Contact Form 7之后(通过functions.php或您的自定义插件)使您的脚本入队,添加一个新函数并将其绑定到DOMSubtreeModified ,然后检查表单是否有错误。

当验证失败时,Contact Form 7的AJAX函数将添加一个span元素,其类别为wpcf7-not-valid-tip (如源代码所示 )。

您可以通过执行以下操作将其定位到您的特定字段:

JS示例:

(function($){
    $('div.wpcf7 > form').submit(function(){
        // The name of a single field you're interested in targeting 
        var fieldName = 'some-field-name';

        $(this).find('span.' + fieldName).bind('DOMSubtreeModified', function(event) {
            // If an error has been appended to this input's parent span, do something
            if ( $(this).children('.wpcf7-not-valid-tip').length ) {
                // RUN YOUR FUNCTION HERE

                // Prevent this function from running multiple times
                $(this).off(event);
            }
        });
    });
})(jQuery);

使用wpcf7_enqueue_scripts将脚本排入wpcf7_enqueue_scripts ,以在默认的Contact Form 7脚本之后排入脚本(您的路径可能会有所不同):

/**
 * Enqueue Scripts with CF7 Dependencies
 */
function so30727367_enqueue_scripts() {
    wp_enqueue_script( 'stackoverflow-scripts', plugin_dir_url(__FILE__) . 'scripts.js', array('jquery'), null, true );
}
add_action( 'wpcf7_enqueue_scripts', 'so30727367_enqueue_scripts' );

您可以利用表单提交事件:

//attach handler on form submit
var formID = "myForm";
$('form#' + formID).submit(catchSubmit);

那么您将需要提交停止表单,并将其自己发布,文件上载情况以及此挂钩中所包含的内容,以及来自服务器的响应都可以在JavaScript中捕获并进行处理:

//custom handler for form submit
                    function catchSubmit(event) {
                        var uploadFileType = $('form#' + formID).attr('enctype') != undefined ? $('form#' + formID).attr('enctype').indexOf('multipart/form-data') != -1 ? true : false : false; //test if form has upload file functionality
                        event.preventDefault(); //stop html form post
                        if (uploadFileType) {
                            //ajax call for model + file upload
                            $.ajax({
                                url: $(this).attr("action"),
                                type: 'POST',
                                data: new FormData(this),
                                success: postSuccessHandler,
                                processData: false,
                                contentType: false
                            });
                            return;
                        }
                        else {
                            // ajax call for simple model/inputs
                            $.post($(this).attr("action"),
                               $(this).serialize(),
                               postSuccessHandler
                               );
                        }
                    }

和成功后处理程序,您可以在其中解释服务器的响应:

function postSuccessHandler(data) {
//do something with returned html, json whatever
}

以下是一些入门代码:

$(function () {
    // Optional nice scroll function
    function scrollTop(myTop){
        var myTop = (typeof myTop==='undefined'||myTop === null) ? 150 : myTop;
        $("html, body").animate({
        scrollTop: myTop
        }, 300);
    }
    $('.wpcf7-form').submit(function(event){
        var valid = true;
        $('[aria-required]').each(function(i,ele){
            if(ele.value == ''){
                $(this).parent().parent().addClass('alert');
                console.log('Required field empty: '+ ele.name);
                valid = false;
            }
        });

        // Handle additional validation here, set valid too false if it does not pass

        if (!valid){
            event.preventDefault();
            scrollTop();
            return false;
        }
        return true;
    });
});

编辑:

或on_sent_ok:“ doFunction();” 链接

或者,您仅可以查看表单在页面加载时是否有错误:

$(function () {
    function checkErrors(){
        var invalid = $('.wpcf7-form').hasClass('invalid');
        var error = $('.wpcf7-form').hasClass('error');
        if (!invalid && !error) {
            return true;
        }
        return false;
    }
    checkErrors();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM