Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Javascript : Keeping radio buttons selected on page refresh

I have responsive css tabs I use to display information in an elegant manner but when user refresh page it goes back to first checked input. I would like to know how to keep the user button selected on page refresh the one who he previously selected. I wrote a script but it does not seem to work.

tabs

  <input class="inputabs" id="tab1" type="radio" name="tabs" checked="checked">
  <label class="labeltabs" for="tab1">Inbox</label>

  <input class="inputabs" id="tab2" type="radio" name="tabs" >
  <label class="labeltabs"for="tab2">Important</label>

  <input class="inputabs" id="tab3" type="radio" name="tabs">
  <label class="labeltabs" for="tab3">Bin</label>

script

<script>
$(document).ready(function(){
    $('.inputabs input[type="radio"]').each(function(){
        $(this).attr("checked",$(this).checked());
    }
);
</script>
like image 780
Sebastian Farham Avatar asked Dec 24 '22 20:12

Sebastian Farham


1 Answers

Will the following work for you requirement:

<!DOCTYPE html>
 <html>
 <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script>
    $(document).ready(function(){
      if(localStorage.selected) {
        $('#' + localStorage.selected ).attr('checked', true);
      }
      $('.inputabs').click(function(){
        localStorage.setItem("selected", this.id);
      });
    });

</script>
 </head>
 <body>
  <input class="inputabs" id="tab1" type="radio" name="tabs" checked="checked">
  <label class="labeltabs" for="tab1">Inbox</label>

  <input class="inputabs" id="tab2" type="radio" name="tabs" >
  <label class="labeltabs"for="tab2">Important</label>

  <input class="inputabs" id="tab3" type="radio" name="tabs">
  <label class="labeltabs" for="tab3">Bin</label>
 </body>
 </html>
like image 133
uautkarsh Avatar answered Dec 26 '22 15:12

uautkarsh