Home › Forums › JavaScript › Unable to store radio button value in localStorage
- This topic is empty.
-
AuthorPosts
-
September 28, 2016 at 3:21 pm #245987gentlemediaParticipant
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!
September 28, 2016 at 3:36 pm #245988Alex ZaworskiParticipantI 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 samevalue
. Here’s a dev tools screenshot showing the issue:September 28, 2016 at 4:07 pm #245989gentlemediaParticipantI 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 :)
September 28, 2016 at 4:43 pm #245990gentlemediaParticipantI’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(); }); });
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.