Unchecking Boxes -- Javascript [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Is there a way to uncheck all boxes at once?
I have a 4x4 table of checkboxes and I set all their ID's to "cb". I want to have a button that clears all of them, so I tried doing something like below:
document.getElementById("cb").checked="false"
But on the screen, they still remain checked. Is this possible?

ID's are unique, so having multiple elements with the same ID wont solve the problem, it will only make your markup invalid. Use classes instead:
var boxes = document.getElementsByClassName("cb");
for (i=0; boxes.length<i; i++) {
boxes[i].checked = false;
}

You can use something like this:
function toggle(state) {
var cb = document.getElementsByName('cb');
for (var i = cb.length; i--;) {
cb[i].checked = typeof state != 'undefined' ? state : !cb[i].checked;
}
}
Usage:
toggle(false); // Uncheck all
toggle(true); // Check all
toggle(); // Toggle all
In this example you select checkboxes by the name attribute. You can also use class name and select inputs with document.getElementsByClassName or document.querySelectorAll methods.
Demo: http://jsfiddle.net/kCmqL/1/

Check this article Javascript Check and Uncheck All Checkboxes
Here is the code below:
Script
<script language="JavaScript">
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
</script>
HTML
<form name="myform" action="checkboxes.asp" method="post">
<b>Your Favorite Scripts & Languages</b><br>
<input type="checkbox" name="list" value="1">Java<br>
<input type="checkbox" name="list" value="2">Javascript<br>
<input type="checkbox" name="list" value="3">Active Server Pages<br>
<input type="checkbox" name="list" value="4">HTML<br>
<input type="checkbox" name="list" value="5">SQL<br>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.myform.list)">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.myform.list)">
<br>
</form>
Best Regards

Try
<script language="javascript">
function checkUnCheckAll(formname)
{
var checkboxes = new Array();
checkboxes = document[formname].getElementsByTagName('input');
for (var i=0; i<checkboxes.length; i++) {
if (checkboxes[i].type == 'checkbox') {
checkboxes[i].checked = false;
}
}
}
</script>
More

You can also your same Name to all controls as below:
<input type="Checkbox" name="compare" id="compare" value="1" />
<input type="Checkbox" name="compare" id="Checkbox1" value="5" />
<input type="Checkbox" name="compare" id="Checkbox2" value="8" />
<input type="Checkbox" name="compare" id="Checkbox3" value="10" />
<input type="button" value="select all" onclick="javascript:checkAll()"/>
<input type="button" value="unckeck all" onclick="javascript: unCheckAll()"/>
<script type="text/javascript">
function checkAll()
{
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = true;
}
}
function unCheckAll() {
var c = document.getElementsByName("compare");
for (var i = 0; i < c.length; i++) {
c[i].checked = false;
}
}
</script>

While you already have an answer, I thought I'd post the following as an option also. Given the following minimal/demonstrative HTML mark-up:
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" />
<input type="checkbox" class="something" name="cb" checked />
<input type="checkbox" class="something" name="cb" checked />
The following JavaScript can be used to check, uncheck or toggle all checkboxes returned by the selector:
Object.prototype.check = function (newState) {
switch (newState.toLowerCase()) {
case 'toggle':
for (var i = 0, len = this.length; i<len; i++){
this[i].checked = !this[i].checked;
}
break;
case 'check':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = true;
}
break;
case 'uncheck':
for (var i = 0, len = this.length; i < len; i++) {
this[i].checked = false;
}
break;
}
return this;
};
To toggle all, call with (for example):
document.getElementsByClassName('something').check('toggle');.
To check all, call with (for example):
document.getElementsByClassName('something').check('check');.
To uncheck all, call with (for example):
document.getElementsByClassName('something').check('uncheck');.

Related

inner html radio button array value getting over written in for loop

I have written this code which should simply display the user's selection based on radio button clicked, There are multiple groups of radio buttons in the one form
<form name="makePicks">
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks1" value="Chiefs"><span>Chiefs</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks1" value="Hurricanes"><span>'Hurricanes'</span>
</label>
<label class="pink">
<input type="radio" name="picks1" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks2" value="Lions"><span>Lions</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks2" value="Stormers"><span>'Stormers'</span>
</label>
<label class="pink">
<input type="radio" name="picks2" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
</form>
<div id="dispPicks">
</div>
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
//var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
document.getElementById("dispPicks").innerHTML="YOU HAVE SELECTED "+radios[i].value
//found = 0;
//break;
}
}
//if (found == 1) {
//alert("Please Select Radio");
//}
//event.preventDefault(); // disable normal form submit behavior
return false;
}
My problem is
The value of the array radios[i].value gets over written as you can see in the image below
In this example cheifs and Stormers both needs to be displayed, since it was selected
If anyone can help me with correct implementation it would be very much appreciated
I created a fiddle at this link https://jsfiddle.net/taditdash/w8hpQ/
You can modify your JavaScript code like this:
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
myradiovalue = "";
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
if (myradiovalue=="")
myradiovalue=radios[i].value
else
myradiovalue=myradiovalue+ ", " +radios[i].value
}
}
document.getElementById("dispPicks").innerHTML = "YOU HAVE SELECTED " + myradiovalue;
return false;
}

Count the number of checked checkboxes in HTML

So basically i want to count the number of checkboxes that are ticked. I get my code to the point where it counts them successfully, but I want to put in an alert that shows the number of checkboxes ticked, the code does this but doesn't show the total count, it increments the total every refresh. I just want to know how I can show a total count.
It should display the total when the radio button 'yes' is clicked.
<br />Apples
<input type="checkbox" name="fruit" />Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onchange="checkboxes()"
function checkboxes(){
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true){
count++;
alert(count);
}
}}
This should do the trick:
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
try this using jquery
Method 1:
alert($('.checkbox_class_here :checked').size());
Method 2:
alert($('input[name=checkbox_name]').attr('checked'));
Method: 3
alert($(":checkbox:checked").length);
Try this code
<br />Apples
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();" />
Javascript
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
alert(count);
}
}
}
FIDDLE DEMO
Thanks to Marlon Bernardes for this.
alert(document.querySelectorAll('input[type="checkbox"]:checked').length);
If you have more than one form with different checkbox names in each, the above code will count all checkboxes in all forms.
To get over this, you can modify it to isolate by name.
var le = document.querySelectorAll('input[name="chkboxes[]"]:checked').length;
The initial code was very nearly right. the line
alert(count);
was in the wrong place. It should have come after the second closing brace like this:-
function checkboxes()
{
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type == "checkbox" && inputElems[i].checked == true){
count++;
}
}
alert(count);
}
In the wrong place it was giving you an alert message with every checked box.
var checkboxes = document.getElementsByName("fruit");
for(i = 0 ; i<checkboxes.length; i++)
{
if(checkboxes[i].checked==0){checkboxes.splice(i,1);}
}
alert("Number of checked checkboxes: "+checkboxes.length);
function checkboxes(){
var inputs = document.getElementsByTagName("input");
var inputObj;
var selectedCount = 0;
for(var count1 = 0;count1<inputs.length;count1++) {
inputObj = inputs[count1];
var type = inputObj.getAttribute("type");
if (type == 'checkbox' && inputObj.checked) {
selectedCount++;
}
}
alert(selectedCount);
}
<html>
<body>Fruits
<br />
<input type="checkbox" name="fruit" checked/>Oranges
<input type="checkbox" name="fruit" />Mango
<input type="checkbox" name="fruit" />Apple
<br />Yes
<input type="radio" name="yesorno" id="yes" onClick="checkboxes();"/>
</body>
</html>

only select one checkbox

I would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.
Thank you!
This is the picture of the part of a menu
<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>
For single selection from multiple options we use Radio Buttons not CheckBoxes.
You should use some thing like this.
<input type="radio" name="option" value="Yes" id="yes" />
<input type="radio" name="option" value="No" id="no" />
But still if you want to go the other way round, Just add the following script in your head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$(this).attr('checked', 'checked');
}
});
});
</script>
Here is the fiddle for above.
Hope this helps.
This looks like a job for radio buttons, not checkboxes.
you got a point to use radio buttons any way here is the javascript solution
i used it in my project when there is search criteria and search result in data grid by
ajax having 13 records when i check one record it disables the rest
code for javascript enable disable check boxes jsfiddle
<form name="mainForm" method="GET">
Visible online?
<input type="checkbox" name="option" value="checkedVisibleOk" id="option" onclick="changeCheckBox();"/>
yes
<input type="checkbox" name="option" value="checkedVisibleNok" id="option" onclick="changeCheckBox();"/>
no
</form>
<script>
var serNoChecked="";
function changeCheckBox() {
try {
var max = document.mainForm.option.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == false) {
document.mainForm.option[i].disabled = true;
}
}
}
else if (count == 0) {
for (var i = 0; i < max; i++) {
document.mainForm.option[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
}
else if (count > 0) {
return false;
}
}
catch (e) {
alert(e.message);
}
}
</script>
Try using Radio Button's, Give them the same name to group them and only allow 1 to be selected:
<td>
<label for="dock_books_search_visible_online"> Visible online?</label>
</td>
<td>
<input type="radio" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" />
</td>
<td>
<label for="dock_books_search_visible_online_yes"> Yes</label>
</td>
<td><input type="radio" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" />
</td>
<td>
<label for="dock_books_search_visible_online_no"> No</label>
</td>
Check this JSFiddle.
Hi why are you using checkbox? Checkboxes are not for the functionality that you want. Radio buttons are exact what you want to use.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
For further details look here
function toggle(chkBox, field) {
for ( var i = 0; i < field.length; i++) {
field[i].checked = false;
}
chkBox.checked = true;
}
<td>
<INPUT type="checkbox" name="xyz" onClick="toggle(this,document.myform.xyz);" value="${incident.incidentID}">
</td>
Use radio buttons and ensure that the name tag is consistent with all options and it'll automatically select just one w/o the need for additional code or JS.

How to disable other checkbox on click of one check box?

I have a group of check boxes with same name, what I need is when I click any one of them, other checkboxes must get disabled. how should I apply Javascript over it?
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
Please help...
You could do
$('input').attr('disabled',true);
...if you really need it. But you might be better off using radio buttons.
Try the demo
<script type="text/javascript">
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].checked !=true)
document.test.finallevelusers[i].disabled='true';
}
</script>
probably you want them enabled again when user uncheck the checkbox
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].disabled ==true)
document.test.finallevelusers[i].disabled='false';
}
<script type="text/javascript">
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}
</script>
</head>
<body>
<form name="aForm" action="">
<p>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
</p>
</form>
<script type="text/javascript">
disableHandler(document.forms.aForm, 'finallevelusers[]');
</script>
Hope This solution helps you-
your DOM could be something like this :
<div class="checkboxes">
<input type="checkbox" name="sameCheck" class="checkbox" id="1" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="2" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="3" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="4" onchange="checkChange()">
</div>
And your logic is this :
let checkbox = document.querySelectorAll('.checkbox')
let b = false;
function checkChange(){
b = !b
if(b){
for(let i = 0 ; i< checkbox.length; i++){
if(checkbox[i].checked === false){
checkbox[i].disabled = 'true';
}
}
}else{
for(let i = 0 ; i< checkbox.length; i++){
checkbox[i].removeAttribute('disabled');
}
}
}
Try code like this
<script>
function uncheck(){
for(var ii=1; ii<=4; ii++){
if(document.getElementById("q6_"+ii).checked==true){
document.getElementById("q6_"+ii).checked=false;
}
}
}
</script>

How to validate for checkbox selection if all checkbox have same name?

Hi All
I have a group of check box having same name so as to get the array of single variable when it is posted on serverside for exampleL
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
<input type="checkbox" name="midlevelusers[]" value="1">
I need a javascript validation to check whether any checkbox is selected or not?
Thanks and Regards
NOTE: I need javascript validation
You can access the DOM elements and check their checked property. For instance:
var list, index, item, checkedCount;
checkedCount = 0;
list = document.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
There we're looking through the whole document, which may not be efficient. If you have a container around these (and presumably you do, a form element), then you can give that element an ID and then look only within it (only the var, form =, and list = lines are new/different):
var form, list, index, item, checkedCount;
checkedCount = 0;
form = document.getElementById('theForm');
list = form.getElementsByTagName('input');
for (index = 0; index < list.length; ++index) {
item = list[index];
if (item.getAttribute('type') === "checkbox"
&& item.checked
&& item.name === "midlevelusers[]") {
++checkedCount;
}
}
Live example
Off-topic: You haven't mentioned using a library, so I haven't used one above, but FWIW this stuff is much easier if you use one like jQuery, Prototype, YUI, Closure, or any of several others. For instance, with jQuery:
var checkedCount = $("input[type=checkbox][name^=midlevelusers]:checked").length;
Live example Other libraries will be similar, though the details will vary.
<form name="myform" method="POST" action="" onsubmit="return checkTheBox();">
<input type="checkbox" name="midlevelusers[]" value="1" /> 1
<input type="checkbox" name="midlevelusers[]" value="2" /> 2
<input type="checkbox" name="midlevelusers[]" value="3" /> 3
<input type="checkbox" name="midlevelusers[]" value="4" /> 4
<input type="checkbox" name="midlevelusers[]" value="5" /> 5
<input type="submit" value="Submit Form" />
</form>
<script type="text/javascript">
function checkTheBox() {
var flag = 0;
for (var i = 0; i< 5; i++) {
if(document.myform["midlevelusers[]"][i].checked){
flag ++;
}
}
if (flag != 1) {
alert ("You must check one and only one checkbox!");
return false;
}
return true;
}
</script>
try,
function validate() {
var chk = document.getElementsByName('midlevelusers[]')
var len = chk.length
for(i=0;i<len;i++)
{
if(chk[i].checked){
return true;
}
}
return false;
}
use id's
<input type="checkbox" name="midlevelusers[]" id="mlu1" value="1">
<input type="checkbox" name="midlevelusers[]" id="mlu2" value="2">
<input type="checkbox" name="midlevelusers[]" id="mlu3" value="3">
<input type="checkbox" name="midlevelusers[]" id="mlu4" value="4">
now you can do
for (var i=1;i<5;i++){
var el = document.getElementById('mlu'+i);
if (el.checked) { /* do something */}
}
This function would alert whether or not a checkbox has any values checked.
function isChecked(checkboxarray){
for (counter = 0; counter < checkboxarray.length; counter++){
if (checkboxarray[counter].checked){
alert("Checkbox has at least one checked");
else{
alert("None checked");
}
You would need to add a bit more to do what you actually want to do with it but that will get you on the right track I think!
You could use jQuery and do it this way:
if($('input[name="light[]"]:checked').length < 1){
alert("Please enter the light conditions");
}

Categories