选择选项保持选中状态。饼干?

时间:2014-03-25 11:24:26

标签: javascript cookies

我有一个非常简单的选择选项,我希望它在点击时触发刷新和特定操作。但在我开始之前,我想知道如何在任何刷新或行动后选择它。

<select name="countries" id="countries" style="width:180px;">
<option value='us'>United States</option>
<option value='gb'>United Kingdom</option>
</select>

任何想法,我都会查看过Cookie,但我会很感激帮助。

3 个答案:

答案 0 :(得分:0)

您必须包含jquery.cookies.js

http://code.google.com/p/cookies/wiki/Documentation

    <script type="text/javascript">
    function change_action(selected_value)
    {
       $.removeCookie("test");
       $.cookie("test", selected_value);
       //make select box selected by placing a id

       //Even this line is not necessary now
       //$('#'+selected_value).attr('selected', true);

       //Provide the URL needs to be redirected
       window.location.href = '';
    }
    </script>

以下是html代码,

//In php check whether cookie is working
   <?php
   echo $_cookie('test');
   ?>
    <select name="countries" id="countries" style="width:180px;" onchange="return change_action(this.value);">
        <option value='us' id="us" <?php if($_cookie('test') == 'us') { ?> ?>selected='selected'<?php } ?>>United States</option>
        <option value='gb' id="gb" <?php if($_cookie('test') == 'gb') { ?> ?>selected='selected'<?php } ?>>United Kingdom</option>
        </select>

答案 1 :(得分:0)

检查这个,在Jquery完成,有一些你可能不需要的代码,这是针对你的选项修改的其他一些问题

  $(document).ready(function(e){
     var name = "Country=";
     var ca = document.cookie.split(';');
     for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) $('#countries').val(c.substring(name.length,c.length));
  }
});

$('#countries').change(function(e)
{
    var cookieVal = "Country="+$(this).val();
document.cookie = cookieVal ;

});

http://jsfiddle.net/AmarnathRShenoy/HM3Zj/2/

答案 2 :(得分:0)

<select name="countries" id="countries" style="width:180px;" onchange="change_language(this.value)">
<option value='us' id='us'>United States</option>
<option value='gb' id='gb'>United Kingdom</option>
</select>

<script>
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}




function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) 
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}


function change_language(lang)
{
setCookie("flag_option_dropdown",current_flag,30);
var flag_current_option_dropdown=getCookie("flag_option_dropdown");
document.getElementById(flag_current_option_dropdown).setAttribute("selected","selected");
}

change_language("gb"); //by default




<script>

你可能正在从事语言翻译工作,我已经用这种方式解决了这个问题。祝你好运