RJP43 / CitySlaveGirls

The Restoration of Nell Nelson
http://nelson.newtfire.org
5 stars 4 forks source link

Checkbox Javascript??? #64

Closed spadafour closed 8 years ago

spadafour commented 8 years ago

How do we toggle elements with a specific class to show/hide via a checkbox? I've been googling solutions, and this is the best I could come up with:

// assign function to onclick property of checkbox
document.getElementById('active').onclick = function() {
    // call toggleSub when checkbox clicked
    // toggleSub args: checkbox clicked on (this), id of element to show/hide
    toggleSub(this, 'active_sub');
};

// called onclick of checkbox
function toggleSub(box, id) {
    // get reference to related content to display/hide
    var el = document.getElementById(id);

    if ( box.checked ) {
        el.style.display = 'block';
    } else {
        el.style.display = 'none';
    }
}
spadafour commented 8 years ago

Okay, I revised the code entirely:

function init() {
    var checks= document.getElementsByTagName("input");
    for (var i = 0; i < checks.length; i++)
    checks[i].addEventListener('click', toggle, false);
}

function toggle() {
    clear()
   var id = this.id;
    switch (id) {
     case "CT": {
            var its = document.getElementsByClassName("CT");
            for (var i = 0; i < cts.length; i++) {
                cts[i].classList.toggle("on")
            }
        };
        break;
        case "WSGC": {
            var wsgcs = document.getElementsByClassName("WSGC");
            for (var i = 0; i < wsgcs.length; i++) {
                wsgcs[i].classList.toggle("on")
            }
        };

    }
  }

function clear() {
    var radios= document.querySelectorAll("g > g");
    /*g > g specifies only g's that are immediate children of g's (not all descendents which would be g g */
    for (var j=0; j< radios.length; j++)
        radios[j].classList.remove("on")

}

window.onload = init;