how to store radio button value in sessionStorage with jquery

1.9k views Asked by At

I have radio button in my navbar and I want to store its value for one session or I can say it automatically retains the same value as user visits different pages of website but resets when browser or tab is closed. What I found is sessionStorage and I tried it but unfortunately its not working, here is my code

  <lab

  console.log($('[type=radio]').length);
  
        $("#option1").click(function() {
          console.log('I am inside radio type'+this.value);
          sessionStorage.setItem('option', this.value);
        });

        $("#option2").click(function() {
          console.log('I am inside radio type'+this.value);
          sessionStorage.setItem('option', this.value);
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <!-- <div class="btn-group btn-group-toggle" data-toggle="buttons"> -->
  <!-- <label class="btn btn-secondary active"> -->
  <input type="radio" value="shop" name="option" id="option1">option1
  <!-- </label> -->
  <!-- <label class="btn btn-secondary"> -->
  <input type="radio" value="product" name="option" id="option2">option2
  <!-- </label> -->
  <!-- </div> -->

el class="btn btn-secondary active"> Option1 Option2

In script what I tried is

$('[type=radio]').click(function() {
        var value = $('[name="option"]').val();
        sessionStorage.setItem('option',value);
});

console.log(sessionStorage.getItem('option'));

Its only printing option1 every time and is it the right way what I want to achieve ?

2

There are 2 answers

0
Abhilash Ravindran C K On

Inside the click event store the value of checked radio button as follows,

 $(function() {
         alert(sessionStorage.getItem('option'));
         $('[type=radio]').click(function() {
                  alert(this.value);           sessionStorage.setItem('option',this.value);
          });    
    });
0
Max Gardner On

The type value needs to be formatted as a string with quotes around it, like below:

$('input[type="radio"]').click(function() { 
    console.log('I am inside radio type'); 
    sessionStorage.setItem('option', this.value); 
});

And if you're loading these buttons dynamically/after loading the script, you can attach the listener to the document object instead:

$(document).on('click', 'input[type="radio"]', function() { 
    console.log('I am inside radio type'); 
    sessionStorage.setItem('option', this.value); 
});