Magnotta
Magnotta

Reputation: 941

Local Storage is returning TypeError: null is not an object

I was just trying to use local storage, the code what I wrote is returning this error TypeError: null is not an object (evaluating 'favorites.length')

<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) {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>

<input type="checkbox" class="faChkRnd" id="like1" />

<input type="checkbox" class="faChkRnd" id="like2" />

<input type="checkbox" class="faChkRnd" id="like3" />

This code should run fine and I'm unable to find out what is causing error

Upvotes: 0

Views: 1525

Answers (1)

Jeanger
Jeanger

Reputation: 92

Put your script after your html lines. What happens is the script assigns a function to the onclick event of a checkbox that is not existing yet.

Upvotes: 1

Related Questions