Skip to Content

cf7LocalStorage()

Utilize localstorage on Contact Form 7 text inputs to make it easier for users to continue filling out previously abandoned forms on future visits.

JavaScript February 7, 2021

Usage

This function runs automatically, so it is not called manually. Is this incorrect?

Source File

Located in /assets/js/modules/forms.js on line 376.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.cf7LocalStorage = function(){
    if ( !jQuery('.wpcf7-form').length ){
        return false;
    }

    jQuery('.wpcf7-textarea, .wpcf7-text').each(function(){
        let thisLocalStorageVal = localStorage.getItem('cf7_' + jQuery(this).attr('name'));

        //Fill textareas with localstorage data on load
        if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') && thisLocalStorageVal && thisLocalStorageVal !== 'undefined' && thisLocalStorageVal !== '' ){
            if ( jQuery(this).val() === '' ){ //Don't overwrite a field that already has text in it!
                jQuery(this).val(thisLocalStorageVal).trigger('keyup');
            }
            jQuery(this).blur();
        } else {
            localStorage.removeItem('cf7_' + jQuery(this).attr('name')); //Remove localstorage if it is undefined or inelligible
        }

        //Update localstorage data
        jQuery(this).on('keyup blur', function(){
            if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') ){
                localStorage.setItem('cf7_' + jQuery(this).attr('name'), jQuery(this).val());
            }
        });
    });

    //Update matching form fields on other windows/tabs
    nebula.dom.window.on('storage', function(e){
        jQuery('.wpcf7-textarea, .wpcf7-text').each(function(){
            if ( !jQuery(this).hasClass('do-not-store') && !jQuery(this).hasClass('.wpcf7-captchar') ){
                jQuery(this).val(localStorage.getItem('cf7_' + jQuery(this).attr('name'))).trigger('keyup');
            }
        });
    });

    //Clear localstorage when AJAX submit fails (but submit still succeeds)
    if ( window.location.hash.includes('wpcf7') ){
        if ( jQuery(escape(window.location.hash) + ' .wpcf7-mail-sent-ok').length ){
            jQuery(escape(window.location.hash) + ' .wpcf7-textarea, ' + escape(window.location.hash) + ' .wpcf7-text').each(function(){
                localStorage.removeItem('cf7_' + jQuery(this).attr('name'));
                jQuery(this).val('').trigger('keyup');
            });
        }
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.cf7LocalStorage = function(){
    //Write your own code here, leave it blank, or return false.
}