[英]Cannot retain checkbox value using jquery.cookie
I use jQuery DataTable
and there is a checkbox
on the toolbar that is used for retrieving all records or not. 我使用
jQuery DataTable
,工具栏上有一个checkbox
,该checkbox
用于检索或不检索所有记录。 As stateSave feature of DataTable
does not work properly, I tried to use jquery.cookie in order to keep the checkbox value after reloading the DataTable
(because the checkbox is redrawn dynamically on every reload) as shown below: 由于
DataTable
stateSave功能无法正常工作,我尝试使用jquery.cookie以便在重新加载DataTable
之后保留复选框值(因为复选框在每次重新加载时都会动态重绘),如下所示:
$(document).ready(function() {
$('#example').DataTable( {
//code omitted for brevity
"serverSide": true,
"ajaxSource": "/Student/GetStudents",
"fnServerData": function (sSource, aoData, fnCallback) {
/* Add some extra data to the sender */
aoData.push({ "name": "isAll", "value": $("#cbIsAll").is(":checked") });
$.getJSON(sSource, aoData, function (json) {
/* Do whatever additional processing you want on the callback, then tell DataTables */
fnCallback(json);
});
},
"fnDrawCallback": function() {
$("div.toolbar").html('<input type="checkbox" id="cbIsAll" name="demo" /> Get all records');
}
});
$(document).on('change', '#cbIsAll', function () {
var isClicked = $('#cbIsAll').is(':checked') ? true : false;
$.cookie('clicked', isClicked, { expires: 1 }); // expires in 1 day
table.ajax.reload();
$('#cbIsAll')[0].checked = ($.cookie('clicked') == "true") ? true : false;
});
});
After debugging the code I saw that although the $('#cbIsAll')[0].checked
line is executed properly as true, the checkbox
lost value later than this line. 调试代码后,我看到尽管
$('#cbIsAll')[0].checked
行已按true正确执行,但checkbox
在此行之后丢失了值。 Could you please clarify me about where the mistake is? 您能给我讲一下错误在哪里吗? Or is there a better and smart way to keep the
checkbox
value? 还是有一种更好,更聪明的方法来保持
checkbox
价值?
There is no reason to use $.cookie
in your case. 没有理由在您的情况下使用
$.cookie
。 In the checkbox change
event, you can simply store the value of the checked state and use that to set the checked
property of the new checkbox generated when you reload the table 在复选框
change
事件中,您可以简单地存储选中状态的值,并使用它来设置重新加载表时生成的新复选框的checked
属性。
var isChecked;
$(document).on('change', '#cbIsAll', function () {
// Store the current value
isChecked = $(this).is(':checked');
....
Then in the datatable's callback function, set the checked state of the checkbox 然后在数据表的回调函数中,设置复选框的选中状态
$('#cbIsAll').prop('checked', isChecked);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.