javascript - How to use a cookie to save the clicked value grab the cookie every time the user opens the page -
i have following code highlight table record 3 different colors when user click checkbox. how can use cookie
save clicked value grab cookie
every time user opens page everytime? haven't no idea how cookies
used. answer appreciate
<!doctype html> <html> <head> <meta charset="utf-8"> <title>untitled document</title> </head> <body> <style> .highlight-red { background-color: red; } .highlight-green { background-color: green; } .highlight-yellow { background-color: yellow; } </style> <div class="col-lg-10"> <table id="table" border="1"> <tr class="highlight"> <td><input type="checkbox" name="cb1" id="cb1" value="y" onchange="changesoma(this, 'red')" /></td> <td>click me</td> </tr> <tr> <td><input type="checkbox" name="cb2" id="cb2" value="y" onchange="changesoma(this, 'green')" /></td> <td>click me</td> </tr> <tr> <td><input type="checkbox" name="cb3" id="cb3" value="y" onchange="changesoma(this, 'yellow')" /></td> <td>click me</td> </tr> </table> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> function changesoma(data, color){ if(data.checked && color == 'red'){ $(data).parent().parent().addclass("highlight-red"); } else{ $(data).parent().parent().removeclass("highlight-red"); } if(data.checked && color == 'green'){ $(data).parent().parent().addclass("highlight-green"); } else{ $(data).parent().parent().removeclass("highlight-green"); } if(data.checked && color == 'yellow'){ $(data).parent().parent().addclass("highlight-yellow"); } else{ $(data).parent().parent().removeclass("highlight-yellow"); } } </script> </body> </html>
localstorage
easier cookie thought . can set , localstorage.setitem or localstorage.getitem
, remain until remove them !!!
<script> var cond = json.parse(localstorage.getitem("check")); for(var in cond) { if(cond[i]) { $("#"+i).attr("checked",true); $("#"+i).parent().parent().addclass("highlight-"+cond[i]); } } function changesoma(data, color){ var state; if(localstorage.getitem("check") == null) { state = {cb1:0,cb2:0,cb3:0}; } else{ state = json.parse(localstorage.getitem("check")); } if(data.checked) { $(data).parent().parent().addclass("highlight-"+color); state[data.id]= color; } else { $(data).parent().parent().removeclass("highlight-"+color); state[data.id]= 0; } localstorage.setitem("check",json.stringify(state)); } </script>
Comments
Post a Comment