Skip to content Skip to sidebar Skip to footer

Save Text In Input To Cookies And Display It To User Everytime He Visits It

I need help with saving the input to cookies and displaying it to the user. I need to make the text in the input to change into the div and display the same text for the user every

Solution 1:

I would recommend setting the cookie with your backend (e.g PHP). However, if you want to only use client-side implementation, you can use js.cookie library.

Here is a simple working code that uses Cookies written and read by javascript only. It listens to the keydown event, so that every letter typed into the input automatically updates the cookie.

Important: Make sure you use a webserver when running it (for example: http://localhost/index.html and not file://c:/index.html. Otherwise cookies won't work.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.js"></script>
<body>
    <input id="name" type="text" class="name" placeholder="What's your name?"/>

    <script>
        $(document).ready(function(){
            var name = Cookies.get('_username');
            if (name) {
                $('#name').val(name);
            }
            $('#name').keydown(function(){
                var inputName = $('#name').val();
                Cookies.set('_username', inputName);
            })
        });
    </script>
</body>
</html>

Post a Comment for "Save Text In Input To Cookies And Display It To User Everytime He Visits It"