简体   繁体   English

如何在jQuery cookie的帮助下在下拉选择框中选择一个值

[英]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. 我正在尝试将选择框值存储在Cookie中。

Users hits the "Default link" then the selected value should be set in cookie. 用户点击“默认链接”,然后应在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'. 为此,我编写了以下代码。但是我不知道如何检索名称为“ language”的提交的cookie。

My doubt : how can I show the currently submitted cookie value as the default selected value in my drop-down ? 我的疑问 :如何在下拉列表中将当前提交的Cookie值显示为默认选择的值?

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>  

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. 然后将选择的值存储到您的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. 上面的代码将选择Java选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM