Reputation: 21
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>
Upvotes: 2
Views: 1419
Reputation: 12864
You don't need javascript.
There is a css selector for this, it's :checked
input[type="radio"]:checked {
/* Use the css of selected class */
}
Upvotes: 2
Reputation: 136
Here is the JSFiddle source https://jsfiddle.net/rj1405/Lnv70bsu/14/
Instead of adding the class name like
this.className += " selected";
I am trying tho add through javascript method
inputs[i].classList.add('selected');
please find the below code for your reference.
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox" || inputs[i].type == "radio") {
if (inputs[i].checked) {
inputs[i].classList.add('selected');
// console.log(inputs[i].classList);
// console.log(inputs[i]);
}
}
}
<input type="radio" name="imgsel" value="" checked="checked" />
<input type="radio" name="imgse2" value="" checked/>
<input type="checkbox" name="vehicle" value="Car" checked>
Upvotes: 0
Reputation: 134
If I understand your code correctly, I would assume you have to change if (inputs[i].type == "checkbox") {
(around line 5) with if (inputs[i].type == "checkbox" || inputs[i].type == "radio" ) {
, then it should also include the radio-buttons.
Upvotes: 0
Reputation: 21
For some reason some plugins in Wordpress removed that data. That's why I want to add an extra class to all the radio buttons and checkboxes. Below an example(this box is now checked):
<input id="payment_method_mollie_wc_gateway_ideal" type="radio" class="input-radio" name="payment_method" value="mollie_wc_gateway_ideal" data-order_button_text="">
Upvotes: 0