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()"/>
Related
I am trying to loop a radio-button form but with no success.
Despite the length of the form is 3 (same as number of radiobuttons) I can not access individual elements.
The purpose is to change the text. Its works If I want to access the first element:
var child = form.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
this returns the first radiobutton text.
But if I create a loop out of this
function getRadioBInfo() {
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var iForm = form[i];
var child = iForm.firstChild;
alert(child.nextSibling.nextSibling.nextSibling.innerHTML);
}
}
.. I get I TypeError: child is null
What is wrong with this code?
HTML
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
I think you are looking for something like following.
var form = document.getElementById("myform");
for (var i = 0; i < form.length; i++) {
var child = form.getElementsByTagName('input')[i];
alert(child.nextSibling.nextSibling.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" name="deliver_form" id="myform" style="display: block;">
<input type="radio" name="delivering" id="radio1" value="deliver"> <label>label1</label><br>
<input type="radio" name="delivering" value="comeandtake"> <label>label2</label><br>
<input type="radio" name="delivering" value="express"> <label>label3</label>
</form>
Since you've tagged jquery, you could use:
$('[name=delivering']).each( function() {
alert( $(this).find('label').html() );
});
To get the label followed after the radio button you could try this:
function getRadioBInfo() {
var form = document.getElementById("myform");
var radios = form.querySelectorAll('input[type=radio]');
var i;
for (i = 0; i < radios.length; i++) {
var radio = radios[i];
console.log(radio.nextSibling.innerHTML);
}
}
getRadioBInfo();
pitfall: there shouldn't be whitespace between the radio or the button. Otherwise nextSibling returns text and not the label
demo
Why you are not getting by name
Try this
function getRadioBInfo() {
var arrRadioBtns = document.getElementsByName("delivering");
for (var i = 0; i < arrRadioBtns.length; i++) {
var btn = arrRadioBtns[i];
alert (btn.value);
}
}
Working Example
form[i] contains only radio buttons.If You want to take the labels Try using
var lbl = document.getElementsByTagName('label');
for (var i=0;i < lbl.length; i++){ lbl[i].innerHTML = 'radio' + i; }
and loop through the labels and change the text
Couple of observation
var form = document.getElementById("myform");
form will not be an array,Instead it will be a String,So you are iteration of the string.length;
You can use doucment.getElementsByName to get all radio buttons with common name
Hope this snippet will be useful
function getRadioBInfo() {
//Retun collection of radio button with same name
var _getRadio = document.getElementsByName("delivering");
// loop through the collection
for(var i = 0;i<_getRadio.length;i++){
//nextElementSibling will return label tag next to each radio input
console.log(_getRadio[i].nextElementSibling.innerHTML)
}
}
getRadioBInfo();
Jsfiddle
This is my code to make check boxes checked with same id
<input type="checkbox" name="MassApprove" value="setuju2" />
<input type="checkbox" name="MassApprove" value="setuju3" />
<input type="checkbox" name="MassApprove" value="setuju4" />
<input type="checkbox" name="MassApprove" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
And This is my javascript code. I need to make this checkboxes as checked when am trigger this function. Help me!..
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
var massApprove = document.getElementById("MassApprove").length();
if (confirmAlert == true) {
//alert(massApproveFlag);
for (var i = 0; i < massApprove; i++) {
document.getElementById("MassApprove").checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
IDs in HTML must be unique.
As you have already specified the name MassApprove, use Document.getElementsByName(),
Returns a nodelist collection with a given name in the (X)HTML document.
Which you can iterate using simple for loop
function doMassApprove(massApproveFlag) {
var confirmAlert = confirm("Do You Need Mass Approve !..");
if (confirmAlert) {
//Get elements with Name
var massApproves = document.getElementsByName("MassApprove");
//Iterate and set checked property
for (var i = 0; i < massApprove.length; i++) {
massApproves[i].checked = true;
}
} else {
document.getElementById("headerMassApprove").checked = false;
}
}
you do not have the same ID and should not since ID must be unique. You have the same NAME and that is fine. -
Do not user getElementById for names, instead use document.getElementsByName which will return a collection you can loop over
Like this
function doMassApprove(massApproveFlag) {
var massApprove = confirm("Do You Need Mass Approve !..");
if (massApprove) {
var checks = document.getElementsByName("MassApprove");
for (var i=0; i < checks.length; i++) {
checks[i].checked = massApprove; // or perhaps massApproveFlag?
}
}
else {
document.getElementById("headerMassApprove").checked = false;
}
}
Just for the heck of it, you can use some modern browser goodness:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), function(cb){cb.checked = true});
and with arrow functions:
Array.prototype.forEach.call(document.querySelectorAll('[name=MassApprove]'), cb => cb.checked=true);
I have three checkboxes. I am already using a piece of code I found here to uncheck the other two when one is checked.
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
I use this inside the checkbox to toggle the state: onchange="cbChange(this)".
However, I also need to provide for a situation where I don't want any of the boxes ticked. While I can do this by adding a separate button or checkbox, I wanted to know if the above code can be modified or another function added that will allow to untick the already ticked box by an onclick event.
I tried adding this function (again found here) but it won't work:
function cbUncheck(obj)
{
if (obj.checked == false)
{
document.getElementByClassName("cb").checked = false;
}
}
I use this in the checkbox code: onclick="cbUncheck(this);"
Suggestions welcome!
Thanks!
you need to check first checkbox checked or not..
if checkbox is not checked then dont need to do anything
otherwise uncheck other checkboxes
<input id="chk1" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk1" >1</label>
<input id="chk2" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk2" >1</label>
<input id="chk3" class="cb" type="checkbox" value="01" onchange='cbChange(this)' />
<label for="chk3" >1</label>
javascript
function cbChange(obj) {
if(obj.checked)
{
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
}
JS BIN JSBIN EXAMPLE
You can use radio buttons so that only one can be selected (no script required for that). Then if some other condition occurs, clear both (below uses a button as an example):
<form>
<input type="radio" name="foo" value="0">zero<br>
<input type="radio" name="foo" value="1">one<br>
<button type="button" onclick="clearRadios(this.form.foo)">Clear radios</button>
</form>
And the function:
function clearRadios(radioGroup) {
for (var i=0; i<radioGroup.length; i++) {
radioGroup[i].checked = false;
}
}
If you don't want users to check the radios at all, disable them.
This below code simply give solutions to what you need.
this.scan=function(index)
{
if( this.boxGroup[ index ].checked )
for(var i=0, g=this.boxGroup, len=g.length; i<len; i++)
if( i != index )
g[i].checked = false;
}
for working demo see jsfiddle
I have two checkbox fields. Using Javascript, I would like to make sure only one checkbox can be ticked. (e.g if one checkbox1 is ticked, if checkbox2 is ticked, checkbox1 will untick)
<input name="fries" type="checkbox" disabled="disabled" id="opt1"/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled"/>
I would also like to have a radio button beneath, if this is clicked, I would like both checkboxes to be unticked.
<input type="radio" name="o1" id="hotdog" onchange="setFries();"/>
Would the best way to do this be by writing a function, or could I use onclick statements?
Well you should use radio buttons, but some people like the look of checkboxes, so this should take care of it. I've added a common class to your inputs:
function cbChange(obj) {
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
obj.checked = true;
}
Demo: http://jsfiddle.net/5uUjj/
Also based on tymeJV's answer above, if you want to only deactivate the other checkbox when one is clicked you can do this:
function cbChange(obj) {
var instate=(obj.checked);
var cbs = document.getElementsByClassName("cb");
for (var i = 0; i < cbs.length; i++) {
cbs[i].checked = false;
}
if(instate)obj.checked = true;
}
tymeJV's function does not let you have both unticked - this does.
(yes, weird but true.. sometimes there's a semantic reason why you want two tickboxes not radio buttons)
Hope this helps:
function setFries(){
var hotdog= document.getElementById("hotdog");
var opt1= document.getElementById("opt1");
var opt2 = document.getElementById("opt2");
if(hotdog.checked){
opt1.checked = false;
opt2.checked = false;
}else if(opt1.checked){
opt2.checked = false;
}else if(opt2.checked){
opt1.checked = false;
}
}
<input type="checkbox" name="fries" id="opt1" disabled="disabled" onclick="setFries(this);/>
<input type="checkbox" name="fries" id="opt2" disabled="disabled" onclick="setFries(this);/>
<input type="radio" name="o1" id="hotdog" onclick="setFries(this);"/>
Note that I am using onclick event:
function setFries(obj){
var fries = document.getElementsByName('fries');
if(obj.id =='hotdog') //Or check for obj.type == 'radio'
{
for(var i=0; i<fries.length; i++)
fries[i].checked = true;
}
else{
for(var i=0; i<fries.length; i++){
if(fries[i].id != obj.id){
fries[i].checked = !obj.checked;
break;
}
}
}
}
The simplest way I found for this was to not use any sort of code at all. I triggered an actions in the check box properties.
1. mouse up to reset a form. I then unselected (for reset) all of my fields accept for my desired check boxes. I then did the same thing for my other check box to go the other way. You can basically turn the check boxes into toggles or have any sort of crazy pattern you want.
I have three checkboxes that looks like this:
<input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
now i wanted to create some ajax (which is working fine) however only the first checkbox has the event:
here is my Jquery function:
$('#image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
So my question is. why is this click function only happening for one of my checkboxes? (if it matters it is only the first checkbox that is working)
ids must be unique on an html page. Instead use a class in the markup and a class selector in jQuery.
HTML
<input class="image_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
Javascript
$('.image_tagging').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
IDs have to be unique change the id to class instead
id="image_tagging"
to
class="image_tagging"
then
$('.image_tagging').click(function(){
in html
<input class="image_tagging" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
in js
$('.image_tagging').click(function(){
// your code
});
id must be unique, use class instead or try this...
$('input[type="checkbox"]').click(function(){
var value = 0;
var websiteID = $(this).attr('class');
if($(this).attr('checked')){
value = 4;
}else{
value = -4;
}
alert('works! '+'id = '+websiteID+" value = "+value );
});
no need to change any HTML code you wrote already...
ID should be unique in your DOM structure. Use class instead of ID for such things.
<input id="image_tagging" class="img_tagging 1" type="checkbox" value="1" checked="checked" name="data[image_tagging]">
And then instead of #image_tagging use .image_tagging for binding click event
$('.image_tagging').click(function(){