2017-04-19 10:01
浏览 109


I have something like this in php:

            $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')};
  localStorage.setItem("favorites", JSON.stringify(favs));

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

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

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 :

    boolean :

    点赞 打赏 评论
  • dqrm8199 2017-04-19 10:27

    You can use submit method.
    You have a form with the submit button and you have to change it to just a regular button.

    And you should put


    to the end of click handler where you save the values to the localStorage.

    Because when you press the submit button it may triggered before your click handler.
    You need save values first and then submit form.

    点赞 打赏 评论

相关推荐 更多相似问题