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 CSS通配符清除内外边距为什么可以覆盖默认样式?
  • ¥15 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的