dongtan3395 2017-04-19 10:01
浏览 115
已采纳

localStorage:自动选中商店复选框

I have something like this in php:

    if(isset($_POST['submit']){ 
            $check = in_array($row['service_object_id'], $values) ? 'checked' : ''; 
    }                       
    echo '<input type="checkbox" class="faChkRnd" id="'.$row['service_object_id'].'" name="list[]" value="'.$row['service_object_id'].'" '.$check.'>';

Each time I press a submit button, it will check the checkboxes with values inside $check. It's working good but I want to store the checkboxes checked in localStorage automatically after pressing the button.

I already use this script to store them after click, but it won't work automatically :

    <script type = "text/javascript"> 
$('.faChkRnd').on('click', function() {
  var fav, favs = [];
  $('.faChkRnd').each(function() { // run through each of the checkboxes
    fav = {id: $(this).attr('id'), value: $(this).prop('checked')};
    favs.push(fav);
  });
  localStorage.setItem("favorites", JSON.stringify(favs));
});

$(document).ready(function() {
  var favorites = JSON.parse(localStorage.getItem('favorites'));
  if (!favorites.length) {return};
  console.debug(favorites);

  for (var i=0; i<favorites.length; i++) {
    console.debug(favorites[i].value == 'on');
    $('#' + favorites[i].id ).prop('checked', favorites[i].value);
  }
});
</script>

Any ideas ? Thank you !

  • 写回答

2条回答 默认 最新

  • dongxuying7583 2017-04-19 10:43
    关注

    you shound check type of favorites[i].value. string or boolean !?

    string :

    if(favorites[i].value == "true") {
        $('#' + favorites[i].id ).prop('checked',true);
    }
    

    boolean :

    $('#' + favorites[i].id ).prop('checked',favorites[i].value);
    

    example :

    string : https://jsfiddle.net/utm4za2p/1/

    boolean : https://jsfiddle.net/utm4za2p/3/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么我按照电路图做出的仿真和实物都不能使用
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web