How to maintain previous checkbox status?

Asked

Viewed 262 times

0

I need to maintain the variable’s previous state checked of input guy checkbox, after the page is loaded. In the current state, every time it is loaded, the checkbox returns to unchecked condition. I would like a solution, through Javascript.

<html>
 <head>
  <title>CSS SWITCH</title>
  <meta charset="UTF-8"> 

  <script type="text/javascript">
   function ChecksVerify() { 
     var aChk = document.getElementsByName("item");   
     for (var i=0;i<aChk.length;i++){   
       if (aChk[i].checked == true){   
         aChk[i].value = "?f=on"; 
       } else { 
         aChk[i].value = "?f=off"; 
       } 
       window.location.assign(aChk[i].value); 
       alert(aChk[i].value + " enviado");
     }
   }  
  </script>

 </head>
 <body>
  <div class="switch__container">
   <p align='center'>
    <input type="checkbox" name="item" onclick="ChecksVerify()">
    <label for="switch-shadow"></label>
   </p>
  </div>
 </body>
</html>
  • The HTTP protocol is stateless (stateless), that is, it does not store the state and each request is made independently of the previous ones, however you can persist the value of checkbox in the user’s browser with localStorage. Knows?

1 answer

1


Add the code below that checks if the page URL contains the parameter ?f=on that will mark the checkbox:

window.onload = function(){
    url_ = location.href;
    if(url_.indexOf("?f=on") != -1){
        document.getElementsByName("item")[0].checked = true;
    }
}
  • always have a naughty way of solving @Dvdsamm... thank you very much... I’m not very familiar with web programming... I really like it is from Assembler.

  • @songrsrs... I tried to study Assembly about 25 years ago but I thought it was a bit complicated. What you develop with Assembler (Assembler and Assembly is the same thing, it is not)?

  • ooopzzzz... heheheheeeee... no, eh!!! sorry me for the primary error... Assembly is the term q I should have Ditto... eh the language! the compiler eh q is called Assembler. well! for at least 45 years I’ve been distracted by it... I think that’s why, it doesn’t seem so complicated to me! nowadays has more utility for microcontrollers than for microprocessors.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.