Jquery cookie保存多个<select> </select>的选择

时间:2014-04-26 17:16:54

标签: jquery cookies html-select

过去似乎曾多次询问这个问题,但由于某些原因问题没有得到答复。

我正在尝试保存多个输入的选择。我正在使用此代码,我在stackoverflow上找到它,但它只保存第一个选择。

$(function() {
  if($.cookie('remember_select') != null) {
    $('.select_class option[value="' + $.cookie('remember_select') + '"]').attr('selected', 'selected');
  }
  $('.select_class').change(function() {
    $.cookie('remember_select', $('.select_class option:selected').val(), {expires: 365, path: '/'});
  });
});

由于

这是我提出的工作解决方案......

<select class="select_class" id="foo" name="foo">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

$(function(){                                                                                      
    var selectbox=$('#setup').find('.select_class'), selectboxCookieName='selection';
        selectbox.each(function(){
        $(this).prop('value', $.cookie(selectboxCookieName + '|' + this.name));
    });

    selectbox.change(function(){
        if(this.value){
            $.cookie(selectboxCookieName + '|' + this.name, this.value,{
                expires: 365
            });
        }else{
            $.removeCookie(selectboxCookieName + '|' + this.name);
        }
    });
});

2 个答案:

答案 0 :(得分:0)

在这种情况下,cookie的值将被某些select元素中的每个更改覆盖。您需要修改cookie保存,以便区分不同的元素。例如:在同一个cookie中保存每个控件{“element1”:“选项1”,“elementX”:“optionY”}的值列表,类似于:

var controlId =  $('.select_class).attr("id"); //assume id is elementX
var controlValue = $('.select_class option:selected').val(); //assume value is optionX
var oldValue = $.parseJSON($.cookie('remember_select'));
var data = {};
data[controlId] = controlValue; //now data is {"elementX":"optionX"}
var newValue = $.extend({}, oldValue, data); //add or replace the value for elementX 
$.cookie('remember_select', JSON.stringify(newValue), {expires: 365, path: '/'});

现在您需要更新适当的代码以检索某些控件的值,例如:

var data = $.parseJSON($.cookie('remember_select')); // json object
var controlValue = data[controlId];

答案 1 :(得分:0)

这是我想出的解决方案......

<select class="select_class" id="foo" name="foo">
  <option value="1">1</option>
  <option value="2">2</option>
</select>

$(function(){                                                                                      
  var selectbox=$('#setup').find('.select_class'), selectboxCookieName='selection';
  selectbox.each(function(){
    $(this).prop('value', $.cookie(selectboxCookieName + '|' + this.name));
  });

  selectbox.change(function(){
    if(this.value){
        $.cookie(selectboxCookieName + '|' + this.name, this.value,{
            expires: 365
        });
    }else{
        $.removeCookie(selectboxCookieName + '|' + this.name);
    }
  });
});