mercredi 23 septembre 2020

Check previous checkboxes when clicking a checkbox and saving all to localstorage

I've been trying to find what I'll explain in a moment, but I only found parts of it and when I tried to put them together, it always failed. Rather than to show what I tried, I think it's better to explain and show a simple example of what I would like and hopefully someone can help me. Here's the example:

<div class="checkbox a">        
    Class A<br>                 
    <input type="checkbox" name="checkbox"  id="a1" value="a1">                 
    <label>A1</label>
    <input type="checkbox" name="checkbox"  id="a2" value="a2">                 
    <label>A2</label>
    <input type="checkbox" name="checkbox"  id="a3" value="a3">                 
    <label>A3</label> 
</div>                          
                        
<div class="checkbox b">        
    Class B<br>                 
    <input type="checkbox" name="checkbox"  id="b1" value="b1">                 
    <label>B1</label>
    <input type="checkbox" name="checkbox"  id="b2" value="b2">                 
    <label>B2</label>
    <input type="checkbox" name="checkbox"  id="b3" value="b3">                 
    <label>B3</label> 
</div>

<div class="checkbox c">
    Class C<br>                 
    <input type="checkbox" name="checkbox"  id="c1" value="c1">                 
    <label>C1</label>
    <input type="checkbox" name="checkbox"  id="c2" value="c2">                 
    <label>C2</label>
    <input type="checkbox" name="checkbox"  id="c3" value="c3">                 
    <label>C3</label>
    <input type="checkbox" name="checkbox"  id="c4" value="c4">                 
    <label>C4</label> 
    <input type="checkbox" name="checkbox"  id="c5" value="c5">                 
    <label>C5</label>  
</div>

PART 1
When you click A3, both A2 and A1 will be checked too. If you check B2, only B2 and B1 will be checked.
Not a button to select all. It kind of works like star ratings perhaps?

PART 2
When I refresh or close and reopen the link, all the checkboxes are still checked in the way I clicked them, so basically I'd like a code that save those choices preferably to the LocalStorage but if you think there's another way that allows me to save the choices, without connecting it to a database or something like that, then it should be okay too.


In all honesty I always had a hard time trying to explain or find what's in my mind, so hopefully all of it makes sense. In this example it only has Class A, B and C, but the thing I want to make will have much more classes. So no matter how many classes it has, it should remember all the checkboxes and unlock the previous checkboxes when clicked.
e.g. when clicking C4, C1 to C3 will also be checked




Aucun commentaire:

Enregistrer un commentaire