动态搜索后如何保持选中的复选框处于选中状态? 每次搜索后,选中的复选框都会被取消选中。
这是我的代码:https://github.com/cdjordje/Test1.git
我尝试了这个,但无法正常工作
jQuery(function(){
if (localStorage.input) {
var checks = JSON.parse(localStorage.input);
jQuery(':checkbox').prop('checked', function(i) {
return checks[i];
});
}
});
jQuery(':checkbox').on('change', function() {
localStorage.input = JSON.stringify(jQuery(':checkbox').map(function() {
return this.checked;
}).get());
});
根据以下说明更新https://github.com/cdjordje/Test1.git中的代码。
更新您的index.php文件
第1步:在index.php文件的脚本中的document.ready之外添加函数
var checked_value_array = [];
function getCheckedValue(THIS){
var temp = $(THIS).val();
if($("#lib_id_"+temp).prop('checked') == true){
checked_value_array.push(temp);
}else{
checked_value_array = checked_value_array.filter(function(item) {
return item !== temp
});
}
}
第2步:将index.php文件中的load_data函数替换为以下函数
function load_data(page, query = '')
{
var temp_arr = JSON.stringify(checked_value_array);
$.ajax({
url:"fetch.php",
method:"POST",
data:{page:page, query:query,temp_arr:temp_arr},
success:function(data)
{
$('#dynamic_content').html(data);
}
});
}
更新您的 fetch.php 文件
第1步:在fetch.php文件中添加以下代码
$checked_value_array = json_decode($_POST['temp_arr']);
第 2 步:将 fetch.php 中的 foreach 循环替换为下面的 foreach 循环
foreach($result as $row)
{
$checked = '';
$id = $row['id'];
if (in_array($id , $checked_value_array)){
$checked = 'checked';
}
$output .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["title"].'</td>
<td><input class="chkCheckBoxId" type="checkbox" id="lib_id_'.$row['id'].'" onclick="getCheckedValue(this)" name="lib_id[]" value="'. $row['id'] .'" '.$checked.'></td>
</tr>
';
}