简体   繁体   中英

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. :)

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 .

you must iterate over the class elements !

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

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

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;
}

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;

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()"/> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM