Dan
Dan

Reputation: 2174

how to make a value to be selected in the dropdown selectbox with help of jquery cookie

I am trying to store the select-box value in my cookie.

Users hits the "Default link" then the selected value should be set in cookie. and when they open my URL, then the default selected value should show them.

For this purpose I have written the below code.but i don't know how can i retrieve the submitted cookie with the name 'language'.

My doubt: how can I show the currently submitted cookie value as the default selected value in my drop-down ?

Please help.

    <html>
        <head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>

    <script>
        $(document).ready(function(){ 
            $('#continue').click(function() {
                 var singleValues = $("#select_letter").val();
                $.cookie("language", singleValues);
            })
        });
    </script>  
        </head>
        <body> 
            <select id='select_letter'>
                <option>Java</option>
                <option>C</option>
                <option>php</option>
                <option>python</option>
                <option>c sharp</option> 
            </select> 
            <a href='/PhtestProject/index.php' id='continue'>Save as default value</a>
                   <!-- On click of this link the current page will load -->
        </body>
    </html>

UPDATE:

<script>
        $(document).ready(function(){  
            $('#continue').click(function() {
                 var singleValues = $("#select_letter").val(); 
                $.cookie("language", singleValues); 
            }) 

         alert($.cookie('language')); //getting the correct value which are set in cookie
         $('#select_letter option[value="'+$.cookie('language')+'"]').attr('selected', 'selected');  //This is not working,Not setting the cookie value as selected

        });
    </script>  

Upvotes: 0

Views: 3061

Answers (1)

diggersworld
diggersworld

Reputation: 13080

If you stick some values on your options:

<select id='select_letter'>
    <option value="java">Java</option>
    <option value="c">C</option>
    <option value="php">php</option>
    <option value="python">python</option>
    <option value="c#">c sharp</option> 
</select> 

Then store the value selected into your cookie. When you get it back just use:

var languageCookieValue = $.cookie('language');
$('#select_letter option[value="' + languageCookieValue + '"]').attr('selected', 'selected');

The above code would select the Java option.

Upvotes: 1

Related Questions