When a button is pressed i'm trying to get all the radio buttons to disable. So far i have set ALL of the ids on the radio buttons to "1"
HTML code:
<input id="1" type="checkbox" name="Q1" value="incorrect"> Bob <br>
<input id="1" type="checkbox" name="Q1" value="incorrect"> Jim <br>
<input id="1" type="checkbox" name="Q1" value="correct"> Callum <br>
JavaScript code:
document.getElementById("1").disabled = true;
However when I test this out it only disables 1 radio button and not all of them. Is there a way to disable them all doing it like i've tried?
Thanks
<input class="checkbox" type="checkbox" name="Q1" value="incorrect"> Bob <br>
<input class="checkbox" type="checkbox" name="Q1" value="incorrect"> Jim <br>
<input class="checkbox" type="checkbox" name="Q1" value="correct"> Callum <br>
Javascript with class:
var x = document.getElementsByClassName("checkbox");
var i;
for (i = 0; i < x.length; i++) {
x[i].disabled = true;
}
You can do it in one line using forEach function.
HTML:
<form if="myForm">
<input id="1" type="checkbox" name="Q1" value="incorrect"> Bob <br>
<input id="1" type="checkbox" name="Q1" value="incorrect"> Jim <br>
<input id="1" type="checkbox" name="Q1" value="correct"> Callum <br>
</form>
JS ES6:
const form = document.querySelector('#myForm');
form.Q1.forEach(cb => (cb.disabled = true));
JS Vanilla:
var form = document.querySelector('#myForm');
form.Q1.forEach(function(cb) {
cb.disabled = true;
});
Since Id's are unique, you shouldnot give same Id to all the buttons, Rather give all the buttons a same class. And then you can run for loop:
var radioButtons = document.getElementsByClassName("your class name");
for(var i=0;i<radioButtons.length;i++) {
radioButtons[i].disabled = true;
}
Use this instead:
<input id="1" type="checkbox" name="Q1" value="incorrect"> Bob <br>
<input id="2" type="checkbox" name="Q1" value="incorrect"> Jim <br>
<input id="3" type="checkbox" name="Q1" value="correct"> Callum <br>
Javascript:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++)
{
if(inputs[i].type == 'checkbox')
{
inputs[i].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.