J. Jesper
J. Jesper

Reputation: 137

How do I disable all radio buttons after select?

I'm trying to disable all radio buttons with a specific name after one has been checked/selected.

This is my try:

var radios = document.getElementsByName("question0");
for (var i = 0, iLen = radios.length; i < iLen; i++) {
  radios[i].onclick = showResult;
}

function showResult() {
  var x = document.getElementsByClassName("checkbox");
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].disabled = true;
  }
}

The problem is that all radio buttons will now be disabled, even those who have the name question1.

And how do I do this to a function for every question? So if I choose one option at question1 I can't change my answer but can still choose at question2.

Upvotes: 0

Views: 2176

Answers (3)

Barmar
Barmar

Reputation: 780909

showResult should just disable the buttons with the same name as the button that was clicked.

  function showResult() {
     var x = document.getElementsByName(this.name);
     var i;
     for (i = 0; i < x.length; i++) {
        x[i].disabled = true;
     }
  }

Make this the click handler of all the radio buttons:

Array.from(document.querySelectorAll("input[type=radio]")).forEach(function(button) {
    button.addEventListener("click", showResult);
});

Upvotes: 0

freginold
freginold

Reputation: 3956

You can disable the whole set of radio buttons by targeting them according to name when one of them is clicked.

See this working example:

var radios = document.querySelectorAll("input[type=radio]");
for (var i = 0, iLen = radios.length; i < iLen; i++) {
  radios[i].onclick = function() {
    showResult(this.name);
  }
}

function showResult(name) {
  var x = document.getElementsByName(name);
  for (var i = 0; i < x.length; i++) {
    x[i].disabled = true;
  }
}
Question 0:
<input type="radio" name="question0" val="answer1">
<input type="radio" name="question0" val="answer2">
<input type="radio" name="question0" val="answer3">

<br /> Question 1:
<input type="radio" name="question1" val="answer1">
<input type="radio" name="question1" val="answer2">
<input type="radio" name="question1" val="answer3">

Upvotes: 3

Devang Patel
Devang Patel

Reputation: 51

Give the same class of all radio button which you want to disable and on class click event you can add attribute disabled

Are you understand?

Upvotes: 0

Related Questions