Boby
Boby

Reputation: 77

Uncheck a Radio button in Javascript using the class

Here are my 2 radios buttons :

 <input type="radio" name="sex" id="Button1" class="Button"/>

 <input type="radio" name="sex" id="Button2" class="Button"/>

When I call a function that countains :

document.getElementById('Button2').checked = false; 

It unchecks the Button2. But I want to uncheck it by using the class

And when the function contains :

document.getElementsByClassName('Button').checked = false;

It does not uncheck the Button2

Why and what is the solution ?

Thank you. :)

Upvotes: 0

Views: 3413

Answers (5)

Wesley Smith
Wesley Smith

Reputation: 19571

You are calling document.getElementsByClassName('Button').checked = false; when it should be document.getElementsByClassName('Button')[1].checked = false;

getElementsByClassName() returns an array

function unCheck(){
  document.getElementsByClassName('Button')[1].checked = false;
}
<input type="radio" name="sex" id="Button1" class="Button" /> 
<input type="radio" name="sex" id="Button2" class="Button" checked/>
<input type="button" value="Uncheck Radio" onclick="unCheck()"/>

Upvotes: 0

Jalaa Zahwa
Jalaa Zahwa

Reputation: 538

you must iterate over the class elements !

   var elements=document.getElementsByClassName('Button');

    Array.prototype.forEach.call(elements, function(element) {
       element.checked = false;
    });

Upvotes: 1

prajmus
prajmus

Reputation: 3271

getElementsByClassName() returns a collection (like an array). So you would actually have to do

document.getElementsByClassName('Button')[1].checked = false;

But you can't be sure that your Button2 is the second element in the array if you have more elements with class Button.

Upvotes: 1

Anirudh Ajith
Anirudh Ajith

Reputation: 927

document.getElementsByClassName returns an nodelist (kind of like an array of these elements)of elements of that class name. So you should cycle through it and change the checked status of each element.

For a generic approach (you can have as many check boxes as you like), use this code.

var allButtons = document.getElementsByClassName("Button");
for (i=0; i<allButtons.length; i++) {
    allButtons[i].checked = false;
}

If you are going to have only 2 elements, you can use

var allButtons = document.getElementsByClassName("Button");
for (i=0; i<2; i++) {
    allButtons[i].checked = false;
}

or

var allButtons = document.getElementsByClassName("Button");
allButtons[0].checked = false;
allButtons[1].checked = false;

Upvotes: 0

Quentin
Quentin

Reputation: 943615

getElementsByClassName returns a node list (which is like an array) not an element.

If you want to do something to every element in the node list, then you have to loop over it and do the thing on each item in the list.

var node_list = document.getElementsByClassName('Button');
for (var i = 0; i < node_list.length; i++) {
    node_list[i].checked = false;
}

Upvotes: 0

Related Questions