Home > Software design >  Remove CSS pseudo element from jQuery form function
Remove CSS pseudo element from jQuery form function

Time:02-12

I developed a contact form for a website.

The field where users enter their message (a textarea box) has a jQuery character counter attached to it.

enter image description here

When the message is sent, an AJAX script refreshes the form and displays a success message.

enter image description here

All good so far.


The problem starts here:

When the user is entering their message and begins to reach the character limit, a warning notice appears, generated as a CSS pseudo element.

enter image description here

When the user exceeds the limit, a restriction notice appears, also generated by CSS.

enter image description here


The problem

When the user sends the message, while the warning notice is displayed, the warning notice won't leave after the page refresh.

enter image description here

This would also be a problem with the restriction notice, but another function disables the send button in this condition, so the form won't send when the counter is in negative territory.

I'm looking for a clean and simple function to integrate with my existing code that will remove the "approaching limit" pseudo element after the form is sent. Thank you.

// 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  ' >'  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>

CodePudding user response:

Inside the ajax success call callback, after clearing the value of the textarea, you can trigger a change event on the textarea. This will in turn trigger .charCount() to reset everything back to defaults. Try this

<!-- 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>

CodePudding user response:

Create a new class to hide these elements. On submit, add this 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");

OR

Just remove these warning/error classes on submit since they must be present for the messages to show up

  • Related