lundi 31 août 2015

How can I make content-dependent checkboxes, with a check-all box in JavaScript?

I have searched for hours, and tried many things, but I can't get it to work. This is my problem: I'm trying to make some sort of summary of a book series I enjoy, in html files (offline, though). And I want to be able to show/hide content based on a few checkboxes at the top of a page. So when I only check the "book 2" checkbox, no content from previous or later books may appear. Secondly I want a check-all button, too. For these 2 things I have 2 scripts, and they do work independently, but when I click the check-all box, the content does not automatically appear, and I'm stuck to why that is. Here's my code (HTML)

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="Scripts.js"></script>
    </head>
<body>
    <p> <input type="checkbox" onchange="ToggleCheck(this);"> Check all</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book0', this);"> Book 0</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book1', this);"> Book 1</p>
    <p> <input type="checkbox" name="bookbox" onchange="ShowHide('Book2', this);"> Book 2</p>
    <p> <span class="Book0">Book 0 content. </span>
        <span class="Book1">Book 1 content. </span>
        <span class="Book2">Book 2 content. </span>
        <span class="Book1">Book 1 content. </span>
    </p>
</body>
</html>

And here's the attached JS file

function ToggleCheck(source) {
    var checkboxes = document.getElementsByName('bookbox');
    for(var i=0, n=checkboxes.length;i<n;i++) {
        checkboxes[i].checked = source.checked;
    }
}

function ShowHide(a, b) {
    var vis = (b.checked) ? "inline" : "none";
    var book = document.getElementsByClassName(a);
    for (var i = 0; i < book.length; i++) {
        book[i].style.display = vis;
    }   
}

I do apologize to sign up for this site just for this, but if someone could help me, I would be very gratefull. Thank you in advance!




Aucun commentaire:

Enregistrer un commentaire