jeudi 23 février 2017

Add class to radio button if checked

I want to add the class 'selected' to both checkboxes and radio buttons if they are checked. I found below code online to make it work with the checkboxes.

What do I need to change to include the radio buttons also in the code?

<script>
                var inputs = document.getElementsByTagName("input");
var checkboxes = [];

for (var i = 0; i < inputs.length; i++) {
  if (inputs[i].type == "checkbox") {
    checkboxes.push(inputs[i]);
    if (inputs[i].checked) {
      checked.push(inputs[i]);
    }
  }
}

for (var j = 0; j < checkboxes.length; j++) {
    checkboxes[j].onclick = function() {
        if (this.checked == true) {
            this.className += " selected";
        } else {
            removeClassName(this, 'selected');
        }
    }
}

function removeClassName(e,t) {
    if (typeof e == "string") {
        e = xGetElementById(e);
    }
    var ec = ' ' + e.className.replace(/^\s+|\s+$/g,'') + ' ';
    var nc = ec;
    if (ec.indexOf(' '+t+' ') != -1) {
        nc = ec.replace(' ' + t + ' ',' ');
    }
    e.className = nc.replace(/^\s+|\s+$/g,'');
    return true;
}
                </script>



Aucun commentaire:

Enregistrer un commentaire