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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?