Javascript 在rails中保持复选框状态

Javascript 在rails中保持复选框状态,javascript,jquery,ruby-on-rails,ruby,Javascript,Jquery,Ruby On Rails,Ruby,我在rails应用程序中有一些复选框,代码如下 <%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%> <%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%> <%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%> <button class="btn

我在rails应用程序中有一些复选框,代码如下

<%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%>
<%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%>
<%= check_box_tag "audio_ids[]",audio.id ,nil,class: "song"%>
<button class="btn btn-warning">play all</button>

<script>
function handleButtonClick(button){
if ($(button).text().match("Check all")){
$(":checkbox").prop("checked", true)
} else {
$(":checkbox").prop("checked", false)
};
updateButtonStatus();
}

function updateButtonStatus(){
var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
$("button").text(allChecked? "Uncheck all" : "Check all");
}

function updateCookie(){
var elementValues = {};
$(":checkbox").each(function(){
elementValues[this.id] = this.checked;
});

elementValues["buttonText"] = $("button").text();
$.cookie('elementValues', elementValues, { expires: 7, path: '/' })
}

function repopulateFormELements(){
var elementValues = $.cookie('elementValues');
if(elementValues){
Object.keys(elementValues).forEach(function(element) {
var checked = elementValues[element];
$("#" + element).prop('checked', checked);
});

$("button").text(elementValues["buttonText"])
}
}

$(":checkbox").on("change", function(){
updateButtonStatus();
updateCookie();
});

$("button").on("click", function() {
handleButtonClick(this);
updateCookie();
});


$.cookie.json = true;
repopulateFormELements();
</script>

全力以赴
功能手柄按钮点击(按钮){
if($(按钮).text().match(“全选”)){
$(“:checkbox”).prop(“选中”,true)
}否则{
$(“:checkbox”).prop(“选中”,false)
};
updateButtonStatus();
}
函数updateButtonStatus(){
var allChecked=$(“:checkbox”).length==$(“:checkbox:checked”).length;
$(“按钮”).text(全部选中?“全部取消选中”:“全部选中”);
}
函数updateCookie(){
var elementValues={};
$(“:复选框”)。每个(函数(){
elementValues[this.id]=this.checked;
});
elementValues[“buttonText”]=$(“button”).text();
$.cookie('elementValues',elementValues,{expires:7,path:'/'})
}
函数重新填充FormElements(){
var elementValues=$.cookie('elementValues');
if(元素值){
key(elementValues).forEach(function(element){
选中的var=元素值[元素];
$(“#”+元素).prop('checked',checked);
});
$(“按钮”).text(elementValues[“buttonText”])
}
}
$(“:复选框”)。在(“更改”,函数()上{
updateButtonStatus();
updateCookie();
});
$(“按钮”)。在(“单击”,函数(){
把手按钮(这个);
updateCookie();
});
$.cookie.json=true;
repopulateFormELements();
他们在刷新页面时保持状态,但每当我来自不同的页面时,他们都会丢失状态。但是当我单独检查这段代码时,它可以工作,但不适用于rails,这段代码有什么问题,我必须做什么