Search code examples
phpjquerycookiessession-cookiessetcookie

How to get a cookie value for input field?


I have a form and I have set cookies to the input fields. I can find the cookies in resources when I go to inspect element. The code is confidential so I can't show how I set my cookies. But I am sure that I can find the selected input fields in resources->cookie.

The same form appears in all the pages. When I redirect from one page to other page the form fields which I selected must appear in all the pages.

I used the below code for getting the cookie value

<script type="text/javascript">
    $(document).ready(function() {
        if(input1 = getCookie("input1 "))
            document.myform.input1.value = input1 ;
    });
</script>

but I am getting error as Uncaught ReferenceError: getCookie is not defined

Can anyone suggest what would be the reason for this error? and how do I get the get cookie value to the input field?


Solution

  • Usually you should google it how to set cookie, not sure if you declare the function as something like getCookie?

    <script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }
    
        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }
    
        $(document).ready(function() {
            setCookie("input1",'1');
            alert(getCookie("input1"));
            document.myform.input1.value = getCookie("input1");
        });
    
    </script>
    

    And Here is the Fiddle http://jsfiddle.net/hr4mubsw/5/

    For more information check this one How do I set/unset cookie with jQuery?

    Hope it may help :)