从 jQuery 表单函数中移除 CSS 伪元素

Remove CSS pseudo element from jQuery form function

我为网站开发了联系表。

用户输入消息的字段(textarea 框)附有 jQuery 个字符计数器。

消息发送后,AJAX 脚本会刷新表单并显示成功消息。

到目前为止一切都很好。


问题从这里开始:

当用户输入消息并开始达到字符数限制时,会出现一个警告通知,生成为 CSS 伪元素。

当用户超过限制时,出现限制通知,同样由CSS生成。


问题

用户发送消息时,在显示警告提示的同时,页面刷新后警告提示不会离开

这也是限制通知的问题,但另一个函数会在这种情况下禁用发送按钮,因此当计数器处于负值区域时表单不会发送。

我正在寻找一个干净简单的函数来与我现有的代码集成,该函数将在发送表单后删除“接近限制”伪元素。谢谢。

// text area character counter
// displays total characters allowed
// displays warning at defined count (currently 150)
// disables submit button when < 0
// max characters that can be input set by maxlength attribute in HTML
(function($) {

    $.fn.charCount = function(submit, options){

        this.submit = submit;

        // default configuration properties
        var defaults = {    
            allowed: 1250,      
            warning: 150,
            css: 'counter',
            counterElement: 'span',
            cssWarning: 'warning',
            cssExceeded: 'exceeded',
            counterText: ''
        }; 
    
        var options = $.extend(defaults, options); 

        function calculate(obj,submit){
        
            submit.attr("disabled", "disabled");

            var count = $(obj).val().length;
            var available = options.allowed - count;
            if(available <= options.warning && available >= 0){
                $(obj).next().addClass(options.cssWarning);
            } else {
                $(obj).next().removeClass(options.cssWarning);
            }
            if(available < 0){
                $(obj).next().addClass(options.cssExceeded);
            } else {
                $(obj).next().removeClass(options.cssExceeded);
                submit.removeAttr("disabled");
            }
            
            $(obj).next().html(options.counterText + available);
        };
        
        this.each(function() {              
            $(this).after('<'+ options.counterElement +' class="' + options.css + '">'+ options.counterText +'</'+ options.counterElement +'>');
            
            calculate(this, submit);

            $(this).keyup(function(){calculate(this,submit)});
            $(this).change(function(){calculate(this,submit)});
        });

    };

})(jQuery);

$(document).ready(function(){   
    $("#modal-contact-form-message").charCount($("#submit_cform"));
});
/* textarea and character counter */

.modalDialog form > #counter-container {}

.modalDialog form > #counter-container > .counter {
    font-size: 1.2em;
    color: #ccc;
    font-family: arial, helvetica, sans-serif   
}
.modalDialog form > #counter-container .warning {
    color: orange;
}

.modalDialog form > #counter-container .warning::after {
    content: " approaching limit";
    font-size: 1em;
}

.modalDialog form > #counter-container .exceeded {
    color: red;
}

.modalDialog form > #counter-container .exceeded::after {
    content: " form won't submit";
    font-size: 1em;
}


/* success and error messages */

#modal-contact-form-responses,
#modal-subscription-form-messages {
    min-height: 30px;
    display: flex;
    justify-content: center;
    align-items: center; 
    margin: 5px 0; 
    font-size: .9em;
}

.success {
    color: black;
    background-color: #dff2bf;
}

.error {
    color: black;
    background-color: #ffbaba;
}
<form action="" method="post" id="modal-contact-form">

  <div>
    <label for="modal-contact-form-name">Name <span>*</span></label>
    <input type="text" name="name_cform" id="modal-contact-form-name" maxlength="75" required>
  </div>

  <div>
    <label for="modal-contact-form-email">E-mail <span>*</span></label>
    <input type="email" name="email_cform" id="modal-contact-form-email" maxlength="75" required>
  </div>

  <div id="subject-line">
    <label for="modal-contact-form-subject">Subject</label>
    <input type="text" name="subject_cform" id="modal-contact-form-subject" maxlength="75">
  </div>

  <div id="counter-container">
    <label for="modal-contact-form-message">Message <span>*</span></label>
    <textarea name="message_cform" id="modal-contact-form-message" maxlength="1500" cols="25" rows="5" required></textarea>
  </div>

  <input type="hidden" name="formtarget_cform" value="modal" id="modal-contact-form-hidden">

  <button type="submit" name="submit_cform" id="modal-contact-form-submit">Send Message</button>

  <p id="modal-contact-form-responses"></p>

</form>

在ajax成功调用回调中,清除textarea的值后,可以触发textarea的更改事件。这将反过来触发 .charCount() 将所有内容重置为默认值。试试这个

<!-- AJAX form messaging -->
<script>            
    $(function() {

        // get the form
        var form = $('#modal-contact-form');

        // get the messages element
        var formMessages = $('#modal-contact-form-responses');

        // set up event listener for contact form
        $(form).submit(function(e) {
            // disable html submit button
            e.preventDefault();

            // serialize form data
            var formData = $(form).serialize();

            // submit form using AJAX
            $.ajax({
                type: 'POST',
                url: $(form).attr('action'),
                data: formData
            })
            .done(function(response) {
                // make sure formMessages element has 'success' class
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');

                // set message text
                $(formMessages).text('Your message has been sent. Thank you!');

                // clear form
                $('input, textarea').val('');
                $("#modal-contact-form-message").trigger('change');
            })
            .fail(function(data) {
                // make sure formMessages element has 'error' class
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');

                // set the message text
                $(formMessages).text('Input error. Please review and re-submit.');
            });

        });

    });
</script>

创建一个新的 class 来隐藏这些元素。在提交时,添加此 class.

.modalDialog form > #counter-container.is-submitting .warning::after,
.modalDialog form > #counter-container.is-submitting .exceeded::after {
    display: none !important;
}
$("#counter-container").addClass("is-submitting");

只需在提交时删除这些 warning/error class,因为它们必须存在才能显示消息