I actually have a pretty simple question, but I've been trying for two days now and I just don't find an answer I need, or maybe I just don't understand it.
That is my problem: I have two rows in a table:
row checkbox
row button
I want the button only be enabled, if the checkbox in the same row is enabled. Picture for better understanding
<input type="checkbox" class="isaimed" name="attr_targeted_checkbox1">
<button type='roll' class="isroll" disabled="true">
I use classes and stumbled across getElementsByClassName
and the fact, that you get an array/node of objects. I tried something like this:
var buttons = document.getElementsByClassName('isroll')
var keyselects = document.getElementsByClassName('isaimed');
for (var i = 0; i < keyselects.length; i++) {
if (keyselects[i].checked == true) {
buttons[i].disabled = false;
break;
}
}
and like 20 other codeparts and functions I found on the web, but it's not working. Maybe I have to assign the rows or something like that? Really, I am just utterly desperate and my mind is full of chunk right now.
Thank you very much for your help!
You need to add an addEventListener
to your input
's to detect when they are clicked on.
Then, with nextElementSibling
, you get the button
and can toggle its state.
Stack snippet
var inputs = document.getElementsByClassName('isaimed'); for (var i = 0; i < inputs.length; i++) { inputs[i].addEventListener('click', function() { if (this.checked) { this.nextElementSibling.removeAttribute("disabled"); // or this.nextElementSibling.disabled = false; return; } this.nextElementSibling.setAttribute("disabled", "disabled"); // or this.nextElementSibling.disabled = true; }) }
<div> <input type="checkbox" class="isaimed" name="attr_targeted_checkbox1"> <button type='roll' class="isroll" disabled="true">Button</button> </div> <div> <input type="checkbox" class="isaimed" name="attr_targeted_checkbox1"> <button type='roll' class="isroll" disabled="true">Button</button> </div> <div> <input type="checkbox" class="isaimed" name="attr_targeted_checkbox1"> <button type='roll' class="isroll" disabled="true">Button</button> </div>
Updated after question edit
In your fiddle the input
and button
aren't siblings, so here is an update that will work for the fiddle version of yours
if (this.checked) {
this.parentElement.nextElementSibling.children[0].disabled = false;
return;
}
this.parentElement.nextElementSibling.children[0].disabled = true;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.