Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Unable to store radio button value in localStorage

  • This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #245987
    gentlemedia
    Participant

    Hi all,

    I have the following snippet that stores text input, textarea and select values in localStorage, but I can’t get get the values of my radio buttons.

    $(function() {
    
        $.each($('.stored'), function() {
            if(localStorage[$(this).attr('name')]) {
                $(this).val(localStorage[$(this).attr('name')]);
            }
        });
    
        $('.stored').on('change', function() {
            localStorage[$(this).attr('name')] = $(this).val(), $(this).find('option:selected').val(), this.checked.val();
        });
    
        // if ($('.stored').is(':checked')) {
        // localStorage[$(this).attr('name')] = $(this).val();
        // };
    
    });
    

    I made pen with this:
    http://codepen.io/gentlemedia/pen/ORgQyr/

    Hopefully someone can see where I go wrong.

    Thanks!

    #245988
    Alex Zaworski
    Participant

    I think this is what’s causing your problem:

    $.each($('.stored'), function() {
      if(localStorage[$(this).attr('name')]) {
        $(this).val(localStorage[$(this).attr('name')]);
      }
    });
    

    Since all of your radio inputs (correctly) have the same name, this is causing each of them to be set to the same value. Here’s a dev tools screenshot showing the issue:

    Radio button issue demo

    #245989
    gentlemedia
    Participant

    I thought it might be in that they have the same name and I tried it to give the radio buttons a unique id and use that to store the values, but also with no success :)

    #245990
    gentlemedia
    Participant

    I’ve got it solved via another forum with the following addition to the snippet

    $(function() {
    
    $.each($('.stored'), function() {
        if(localStorage[$(this).attr('name')]) {
            if ($(this).is(':radio')) {
                if($(this).val() == localStorage[$(this).attr('name')]) {
                    $(this).prop('checked', true);    
                }
            } else {
                $(this).val(localStorage[$(this).attr('name')]);
            }
        }
    });
    
    $('.stored').on('change', function() {
        localStorage[$(this).attr('name')] = $(this).val(), $(this).find('option:selected').val();
    });
    
    });
    
Viewing 4 posts - 1 through 4 (of 4 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.