Parsing Multi-Variable Cookies into Web Form Value

2019-08-01 12:18发布

I realize that FireFox, Chrome, Safari, & Opera can limit the number of cookies a domain/website can set. So I thought of a different approach to storing my web forms many text, radio buttons, and select box values -Set a multi-variable cookie for each major section of the web form, instead of a separate cookie for each variable.

It would look something like this (inside each cookies content)...

firstName=John;&&;lastName=Andrews;&&;streetAddress=1234 Memory Ln.

What I'm looking for is a JavaScript function that will create/update this type of cookie on-the-fly properly (using element names instead of ID's for max compatibility with radio buttons) , triggered on each form elements 'onchange' event.

Then when needed, a function to load the cookie into a JavaScript string variable, parse the string for actual variables from between ';&&;' and load them into real JavaScript variables by the corresponding name, then when the user returns to the form the JavaScript fills in the values of the corresponding (by same name) form elements with these values, automatically.

Any help would be greatly appreciated.

Thanks in Advance!!

-James A.

1条回答
趁早两清
2楼-- · 2019-08-01 12:51

FULL SOLUTION BELOW : Here is the complete 'save_form.js' code!

//<!-- Prerequisites: jquery.min.js -->

//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [BEGIN] -->
function set_cookie ( name, value, path, domain, secure )
    {
        var cookie_string = name + "=" + escape ( value );

        var cookie_date = new Date();  // current date & time ;

        var cookie_date_num = cookie_date.getTime(); // convert cookie_date to milliseconds ;
        cookie_date_num += 35 * 60 * 1000;  // add 35 minutes in milliseconds ;
        cookie_date.setTime(cookie_date_num); // set my_date Date object 35 minutes forward ;


        cookie_string += "; expires=" + cookie_date.toGMTString();


        if ( path )
            cookie_string += "; path=" + escape ( path );

        if ( domain )
            cookie_string += "; domain=" + escape ( domain );

        if ( secure )
            cookie_string += "; secure";

        document.cookie = cookie_string;

    };
//<!-- A script to set a cookie [Argument(s) accepted: Cookie Name, Cookie Value, etc.] [END] -->

//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [BEGIN] -->

function get_cookie ( cookie_name )
    {
        var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

        if ( results )
            { 
            return ( unescape ( results[2] ) ); 
            }
    else
            {
            return null;
            };
    };

//<!-- A script to grab a cookies value by name [Argument(s) accepted: Cookies Name] [END] -->


function populateCookieFromForm ( cookieName ) {

    var encodedCookie;

    var preCookieObj = '{';

    var allMainElements = $('form').find('input[type=text], select');

    for (var i=0; i < allMainElements.length; i++) 
        {

            preCookieObj = preCookieObj + '"' + allMainElements[i].name +'":"'+ allMainElements[i].value +'",';     

        };

    preCookieObj = preCookieObj.substring(0, preCookieObj.length - 1);
    preCookieObj = preCookieObj + '}';

    //<!-- btoa() encodes 'string' argument into Base64 encoding --> 
    encodedCookie = btoa( preCookieObj );

    set_cookie(cookieName, encodedCookie);

};

function populateFormFromCookie (cookieName) {


    if ( ! get_cookie ( cookieName ) )

        {

        //<!-- Do Nothing - No Cookie For this form set. -->

        }
    else 
        {
            //<!-- atob() decodes 'string' argument from Base64 encoding --> 
            jSONCookieObj = atob( get_cookie ( cookieName ) ) ;     

            jSONObj = JSON.parse( jSONCookieObj );

            var allMainElements = $('form').find('input[type=text], select');

            for (var i=0; i < allMainElements.length; i++)  
            {

                var elementName = allMainElements[i].name;

                var elementValue = jSONObj[elementName];

                allMainElements[i].value = elementValue;

            };

        };


};


function populateCookieFromRadios (cookieName) {
    var radioState={};

    $(':radio').each(function(){
    if(!radioState[this.name]){
    radioState[this.name]={};
    }    
    radioState[this.name][this.value]=this.checked;
    });


    /* stringify to JSON and convert to Base64 */
    var storeString= btoa(JSON.stringify(radioState));

    /* store in cookie*/
    set_cookie(cookieName, storeString);

};


function populateRadiosFromCookie (cookieName) {

    if ( ! get_cookie ( cookieName ) )

        {

        //<!-- Do Nothing - No Cookie For this form set. -->

        }

    else
        {

            var cookieString = get_cookie ( cookieName );
            var newPageState= JSON.parse(atob(cookieString));

            /* loop through radios setting state */
            $(':radio').prop('checked',function(){
            return newPageState[this.name][this.value];    
            });

        };
};

This is how you properly call these functions. Near the bottom of the HTML/PHP page containing the form, place this JavaScript respectively:

<script type="text/javascript">

//<!-- If returning user detected, populate form with cookie values [BEGIN] -->

populateFormFromCookie('thisForm');
populateRadiosFromCookie('thisFormRadios');
//<!-- If returning user detected, populate form with 'section' cookie values [END] -->

//<!-- On change of ALL form elements re-save form cookie(s) [BEGIN] -->

$('input[type=radio]', $('form')).on('change',function(e){

        populateCookieFromRadios('thisFormRadios');

    });

$('input[type=text], select, textarea', $('form')).on('change',function(e){

        populateCookieFromForm('thisForm');

    });

$('input[type=text]', $('form')).on('input',function(e){     

        populateCookieFromForm('thisForm');

    });
//<!-- On change of ALL form elements re-save form cookie(s) [END] -->

</script>

The next task is to see if all of this can be done without jQuery...hmm...

查看更多
登录 后发表回答