I'm looking for a native JavaScript Solution that will prevent the user checking more than 2 items by disabling the remaining checkboxes (and enabling them again if the user unchecks one of their options)
Below are the checkboxes I have in place:
<div class="checkboxdiv">
<input type="hidden" name="Extras" value="">
<input type="checkbox" name="Extras" value="Wedges"><label>Wedges</label> <br/>
<input type="checkbox" name="Extras" value="Chips"><label>Chips</label> <br/>
<input type="checkbox" name="Extras" value="Garlic Bread"><label>Garlic Bread</label> <br/>
<input type="checkbox" name="Extras" value="Chicken Wings"><label>Chicken Wings</label> <br/>
<input type="checkbox" name="Extras" value="Cheese Sticks"><label>Cheese Sticks</label>
</div>
I am aware this has been covered using JQuery, but I'm looking for a native solution so I can better understand how the code works.
Solution
This is the final solution I have come up with, through everyone's help.
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup;
var limit=limit;
//Changes onclick funtion for each checkbox
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick= function(){
var checkedcount=0;
//Loops through checkboxes
for (var i=0; i<checkgroup.length; i++){
//adds 1 if checked, 0 if not
checkedcount+=(checkgroup[i].checked)? 1 : 0;
}
//Loops through checkboxes
for (var i=0; i<checkgroup.length; i++){
//Disables check box if it's unchecked and the limit has been reached
if(!checkgroup[i].checked && checkedcount==limit){
checkgroup[i].disabled=true;
}
//Enables all checkboxes otherwise
else{
checkgroup[i].disabled=false;
}
}
}
}
}
Check out the CSS pseudo class ":checked" and document.querySelectorAll.
Here is a fiddle to start from:
var currentlyCheckedCount = 0
function disableRemainingCheckboxes() {
Array.from(document.querySelectorAll('input[type="checkbox"]:not(:checked)')).forEach(function(element) {
element.disabled = 'disabled'
})
}
function enableAllCheckboxes() {
Array.from(document.querySelectorAll('input[type="checkbox"]')).forEach(function(element) {
element.disabled = undefined
})
}
Array.from(document.querySelectorAll("input[type='checkbox']")).forEach(function(checkbox) {
checkbox.addEventListener('change', onCheckboxClick)
})
function onCheckboxClick() {
if(this.checked) {
currentlyCheckedCount++
} else {
currentlyCheckedCount--
}
if(currentlyCheckedCount == 2) {
disableRemainingCheckboxes()
} else {
enableAllCheckboxes()
}
}
Geekonaut answer/code is great, but, if you care about IE support (Array.from() doesn't work in it), here is simplified, more straight-forward version:
limit = 0; //set limit
checkboxes = document.querySelectorAll('.checkboxdiv input[type="checkbox"]'); //select all checkboxes
function checker(elem) {
if (elem.checked) { //if checked, increment counter
limit++;
} else {
limit--; //else, decrement counter
}
for (i = 0; i < checkboxes.length; i++) { // loop through all
if (limit == 2) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = true; // and disable unchecked checkboxes
}
} else { //if limit is less than two
if (!checkboxes[i].checked) {
checkboxes[i].disabled = false; // enable unchecked checkboxes
}
}
}
}
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].onclick = function() { //call function on click and send current element as param
checker(this);
}
}
<div class="checkboxdiv">
<input type="hidden" name="Extras" value="">
<input type="checkbox" name="Extras" value="Wedges"><label>Wedges</label> <br/>
<input type="checkbox" name="Extras" value="Chips"><label>Chips</label> <br/>
<input type="checkbox" name="Extras" value="Garlic Bread"><label>Garlic Bread</label> <br/>
<input type="checkbox" name="Extras" value="Chicken Wings"><label>Chicken Wings</label> <br/>
<input type="checkbox" name="Extras" value="Cheese Sticks"><label>Cheese Sticks</label>
</div>
Code is very clear (easy to understand), i hope, and there are comments, too.
Related
I iterate through an array to create some checkboxes, like below:
<div class="funnels">
<label class="checkbox-inline">
<input type="checkbox" id="selectall"> onClick="selectAll(this)" />All funnels
</label>
<?php foreach ($funnels as $funnel) { ?>
<label class="checkbox-inline">
<input type="checkbox" name="funnel[]" id ="funnel" value="<?php echo $funnel ?>" ><?php echo $funnel ?>
</label>
<?php } ?>
</div>
I use the following javascript to select all checkboxes when the All checkbox has been clicked. What I need to do is to unselect the all checkbox once one of the other checkboxes has been unchecked.
Any help would be appreciated.
function selectAll(source) {
checkboxes = document.getElementsByName('funnel[]');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
The id should be unique; so consider using class instead of id.
function selectAll(source) {
checkboxes = document.querySelector('funnel[]');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
function selectAll(source) {
var checkboxes = document.querySelectorAll('.funnel');
for(i=0;i<checkboxes.length;i++)
checkboxes[i].checked = source.checked;
}
function unSelect(element) {
if(!element.checked){
// uncheck "select all" when 1,2 or 3 is unchecked
document.querySelector('#selectall').checked = false;
// if you want to unselect also the others checkboxes of the class "funnel",uncomment the following block
/*var others = document.querySelectorAll('.funnel');
for(i=0;i<others.length;i++)
others[i].checked = false;*/
}else{
// check "select all" when 1, 2, 3 is checked
document.querySelector('#selectall').checked = true;
}
}
<input type="checkbox" onclick="selectAll(this)" id="selectall"/> all select <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 1 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 2 <br>
<input type="checkbox" class = "funnel" onclick="unSelect(this)"/> 3 <br>
You would need to bind change event handler to other checkbox element's also.
I would also recommend you to use unobtrusive event handlers see addEventListener()
document.addEventListener("DOMContentLoaded", function(event) {
var checkboxes = document.getElementsByName('funnel[]'),
selectall = document.getElementById('selectall');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function() {
//Conver to array
var inputList = Array.prototype.slice.call(checkboxes);
//Set checked property of selectall input
selectall.checked = inputList.every(function(c) {
return c.checked;
});
});
}
selectall.addEventListener('change', function() {
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = selectall.checked;
}
});
});
<label> <input type="checkbox" id="selectall" />All funnels</label>
<br><label> <input type="checkbox" name="funnel[]" value="1">1</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">2</label>
<br><label> <input type="checkbox" name="funnel[]" value="2">3</label>
Refrences
DOMContentLoaded
Array.every()
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;
}
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>
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>
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");
}