Limit the number of check-boxes allowed to be checked - javascript

function CountChecks(whichlist,forarray,maxchecked,latestcheck) {
// An array containing the id of each checkbox to monitor.
// List the id of each checkbox in the set. If more than
// one set, list other sets in their own arrays. The
// array name to use is passed to this function.
*// THIS PART IMPORTANT*//
var listone = new Array("1", "2", "3", "4", "5", "6");
*// THIS PART IMPORTANT*//
// End of customization.
var iterationlist;
eval("iterationlist="+whichlist);
var count = 0;
for( var i=0; i<iterationlist.length; i++ ) {
if( document.getElementById(iterationlist[i]).checked == true) { count++; }
if( count > maxchecked ) { latestcheck.checked = false; }
}
if( count > maxchecked ) {
alert('Sorry, only ' + maxchecked + ' may be checked.');
}
}
This is you can see CHECKBOX CHECK LIMITER.. And you can see works with function. I wanna do send this to js file from the page.. but Its not very functional becouse of array part. It has to create array's own by own.. I add the variable function part 'forarray'.. I dont know javascript and Im asking you it has to be like this when it create own arrays.
var {whichlist variable} = new Array({forarray variable list});
And HTML code like this.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','1',3,this)" value="2x2">2x2
<input id='2' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','2',3,this)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','3',3,this)" value="2x3">2x3
<input id='4' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','4',3,this)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','5',3,this)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','6',3,this)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','7',2,this)" value="red">Red
<input id='8' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','8',2,this)" value="gold">Gold
<input id='9' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','9',2,this)" value="green">Green
<input id='10' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','10',2,this)" value="silver">Silver
<input id='11' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','11',2,this)" value="blue">Blue
</p>

You do not need to do all of that. All you need to do is pass a reference to the element into the function and then use its name to query a list of its siblings. Count the number of checked boxes and prevent any others from being checked.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="listone" onclick="javascript:checkNumChecked(this, 3)"
value="2x2">2x2
<input id='2' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x3">2x3
<input id='4' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="red">Red
<input id='8' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="gold">Gold
<input id='9' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="green">Green
<input id='10' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="silver">Silver
<input id='11' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="blue">Blue
</p>
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
if (checked > limit) {
siblings[ct].checked = false
alert('Sorry, only ' + limit + ' item(s) may be checked.');
break;
}
}
}
</script>
However, alerts are annoying to end users. A much better way of doing this is to disable the other check boxes once the limit has been reached and re-enable them when a box is unchecked.
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>
To have the same, but make it work using only ids you can do the following:
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = [], checked = 0, item_num = parseInt(ele.id),
sct = (item_num < 7) ? 1 : 7, ect = (item_num < 7) ? 6 : 11;
for (ct = sct; ct <= ect; ct++) {
siblings.push(document.getElementById(ct));
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>

Related

How get the sum of all the checkbox values of checked items

let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function() {
if (addonCheckboxes[i].checked != false) {
priceSection.textContent = parseInt(customProductPricing) + parseInt(addonCheckboxes[i].getAttribute("price"));
} else {
priceSection.textContent = parseInt(customProductPricing)
}
})
}
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<input class="custom-checkbox" type="checkbox" price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
I want to get the total of all the checkboxes if they are all checked. So far it gives only one value. And need to deduct the prices if the checkbox is unchecked.
This one has fixed all the errors you made in your markup, and simplified the code by alot.
const output = document.getElementById('priceSection');
const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);
document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>
You are overwriting instead of summing. When you are iterating through an array of checkboxes and you find that more than one is checked your function fails.
You should firstly count the sum of checked checkboxes and then send it to priceSection, and when your sum is equal to zero you should set it parseInt(customProductPricing) like you did in else.
When the change event of the <input> elements is triggered, the update() method is called and the values in the page are collected and printed on the page. I don't understand the issue of lowering the price if the checkbox is not selected. Update the update() method to subtract unselected values from the total using the following approach; Add an else statement to the if block.
(function() {
let addonCheckboxes = document.querySelectorAll(".custom-checkbox");
function update()
{
let total = parseInt(document.getElementById("customProductPricing").textContent);
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
if(addonCheckboxes[i].checked == true)
total += parseInt(addonCheckboxes[i].value);
document.getElementById("priceSection").innerHTML = "Result: " + total;
}
for(let i = 0 ; i < addonCheckboxes.length ; ++i)
addonCheckboxes[i].addEventListener("change", update);
})();
<input class="custom-checkbox" type="checkbox" value="10"/>
<label>10</label>
<input class="custom-checkbox" type="checkbox" value="20"/>
<label>20<label>
<input class="custom-checkbox" type="checkbox" value="30"/>
<label>30<label>
<!-- Static Value -->
<div id="customProductPricing">40</div>
<br><div id="priceSection" style="color: red;">Result: </div>
Using data set you can access price
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing")
let sum = 0
for (let i = 0; i < addonCheckboxes.length; i++) {
addonCheckboxes[i].addEventListener("change", function(e) {
console.log(e.target.dataset.price)
if (addonCheckboxes[i].checked != false) {
sum = sum +Number(e.target.dataset.price)
} else {
sum = sum -Number(e.target.dataset.price)
}
customProductPricing.innerHTML = sum
})
}
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<input class="custom-checkbox" type="checkbox" data-price="150"></input>
<div id="priceSection">
</id>
<div id="customProductPricing">"150"</div>
As #Sercan has mentioned... I am also not sure about the issue of loweing the sum but I've whipped up something for you.
Hopefully it'll lead you to what you want to achieve.
let addonCheckboxes = document.querySelectorAll(".custom-checkbox")
let priceSection = document.getElementById("priceSection")
let customProductPricing = document.getElementById("customProductPricing");
var checkboxes = document.getElementsByClassName("custom-checkbox");
function sum(){
var total = 0;
for(let x = 0; x < checkboxes.length; x++){
let price = document.getElementsByClassName(x);
if(price[0].checked){
total = total + Number(price[0].dataset.price);
}
}
console.log('Sum = ' + total)
}
<input class="custom-checkbox 0" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 1" onclick="sum()" type="checkbox" data-price="150"></input>
<input class="custom-checkbox 2" onclick="sum()" type="checkbox" data-price="150"></input>
<div id="priceSection"></id>
<div id="customProductPricing">"150"</div>

How to search different digits in numbers

I have a function which split the input value on space and I looped through to search them in a number but only the last value is shown (checked) not the other before it .
One solution can be by removing else that way it worked fine but this way when changing the value the checked number remain intact(last searched result are also shown).
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var reader = document.getElementsByClassName("checkbox_inputs")
for (let i = 0; i < reader.length; i++) {
var readerText = reader[i].value
var readerText1 = readerText.trim()
var reed = document.getElementById("allNumbers").value;
var reed1 = reed.trim()
var myDiffValues = reed1.split(" ");
document.getElementById("demo").innerHTML = myDiffValues
if (reed != '') {
for (var item of myDiffValues) {
if (readerText1.indexOf(item) > -1) {
reader[i].checked = true;
} else {
reader[i].checked = false;
}
}
} else {
reader[i].checked = false;
}
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>
One strange behavior it is showing is when lot of space is entered in the input all checkboxes get checked
You can make it much more easily :)
Explanation
First of all you read your inputs (checkbox_inputs).
Then you
read just once the numbers (allNumbers) and you can trim and split
in one line.
Last step: for each one of your checkboxes you set the checked value if the allNumbers list includes the expected value. false otherwise.
Working Example
let SearchingNumbers_btn = document.getElementById('SearchingNumbers_btn');
SearchingNumbers_btn.addEventListener("click", refree);
function refree() {
var inputs = document.getElementsByClassName("checkbox_inputs");
var allNumbers = document.getElementById("allNumbers").value.trim().split(" ");
document.getElementById("demo").innerHTML = allNumbers
for (let i = 0; i < inputs.length; i++) {
inputs[i].checked = allNumbers.includes(inputs[i].value);
}
}
<input type="text" name="" id="allNumbers" />
<button id="SearchingNumbers_btn">Select all</button>
<br><br>
<br>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2528" data-u-mobile="2528" />
<span>2528</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2529" data-u-mobile="2529" />
<span>2529</span>
<input class="checkbox_inputs" type="checkbox" name="sending" class="Sending_JS" value="2527" data-u-mobile="2527" />
<span>2527</span>
<div id="demo"></div>

How can I add up my selection lists, radios, and checkboxes to total?

I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById

How to add the input values of eight labels to an array, then get the prime numbers of the array? Javascript

I'm very new in the javascript and I want to put the values of 8 labels (text) to an array of 8 numbers, then get the prime numbers of the array, I can make the array and I can set the 8 labels in the html, but I'm not sure with taking that values to the array. If you could help me it will be awesome, thanks!
The code of my solver button:
$('#btn1').click(function () {
var primes = [true, true, true, true, true, true, true, true];
var limit = Math.sqrt(8);
for (var i = 1; i < 8; i++) {
if (primes[i] === true) {
for (var j = i * i; j < 8; j += i) {
primes[j] = false;
}
}
}
for (var i = 1; i < 8; i++) {
if (primes[i] === true) {
console.log(i + " " + primes[i]);
}
}
});
The code of the labels:
<label>1. </label> <input id="input1" type="text"><br>
<label>2. </label> <input id="input2" type="text"><br>
<label>3. </label> <input id="input3" type="text"><br>
<label>4. </label> <input id="input4" type="text"><br>
<label>5. </label> <input id="input5" type="text"><br>
<label>6. </label> <input id="input6" type="text"><br>
<label>7. </label> <input id="input7" type="text"><br>
<label>8. </label> <input id="input8" type="text"><br>
Code to check if number is prime (from: https://stackoverflow.com/a/24094774/1013526):
function isPrime(n) {
// If n is less than 2 or not an integer then by definition cannot be prime.
if (n < 2) {return false}
if (n != Math.round(n)) {return false}
// Now assume that n is prime, we will try to prove that it is not.
var isPrime = true;
// Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {isPrime = false}
}
// Finally return whether n is prime or not.
return isPrime;
}
Code for the solver button click:
$('#btn1').click(function () {
var count = 8; // in case you decide to change this later
var primes = {}; // object instead of array
for (var i = 1; i < count; i++) {
var value = $('#input'+i).val(); // get the input value;
value = parseInt(value); // convert it from string to int.
primes[i] = {};
primes[i].value = value;
primes[i].isPrime = isNan(value) ? false : isPrime(value);
$('#result'+i).text(primes[i].isPrime ? 'Prime' : 'Not Prime');
}
console.dir(primes); // log output to console.
$('#container2').html(JSON.stringify(primes)); // output to container2 as string
});
The code of the labels (modified):
<label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
<label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
<label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
<label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
<label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
<label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
<label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>
If you want to make the output a little more pretty you could do something like this:
var output = '<pre>';
for (var i in primes) {
output += primes[i].value + ': ' + primes[i].isPrime + "\n";
}
output += '</pre>';
$('#container2').html(output);
You don't need to create an array and iterate over each element in the array. Instead, you can just write a function to check whether the passed label is a prime number or not. If it is prime, fill the HTML. I have written my function in PHP but the logic is same for javascript.
function is_prime($number)
{
if ($number==1)
return false;
if ($number==2)
return true;
$sqrt = sqrt($number);
$floor = floor($sqrt);
for ($i=2 ; $i <= $floor ; $i++)
{
if ($number % $i == 0)
{
return false;
}
}
return true;
}
$start = 1;
$labels = 8;
for($i = 1; $i <= $labels; $i++)
{
if(is_prime($i))
{
echo '<label>'.$i.'. </label>'.'<input id="input'. $i.'" type="text" value=" '. $i .'">'.'<br>';
}
}
// output
2. 2
3. 3
5. 5
7. 7
Hope this helps !
Here's my entire HTML:
<script>
$(document).ready(function(){
$('#btn1').click(function () {
var count = 8; // in case you decide to change this later
var primes = {}; // object instead of array
for (var i = 1; i < count; i++) {
var value = $('#input'+i).val(); // get the input value;
value = parseInt(value); // convert it from string to int.
primes.i.value = value;
primes.i.isPrime = isNan(value) ? false : isPrime(value);
$('#result'+i).text(primes.i.isPrime ? 'Prime' : 'Not Prime');
}
$('#container2').html(primes); // log output to console.
});
function isPrime(n) {
// If n is less than 2 or not an integer then by definition cannot be prime.
if (n < 2) {return false}
if (n != Math.round(n)) {return false}
// Now assume that n is prime, we will try to prove that it is not.
var isPrime = true;
// Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {isPrime = false}
}
// Finally return whether n is prime or not.
return isPrime;
}
});
</script>
</head>
<body>
<center><h2>Prime Numbers Calculator.</h2><br></center>
<div class="well">
<div class="container" id="container1">
<div class="col-md-4">
<label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
<label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
<label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
<label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
<label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
<label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
<label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>
</div>
<div class="col-md-4">
<div class="container" id="container2">
</div>
</div>
<div class="col-md-4">
<div class="container" id="container3">
</div>
</div>
</div>
</div>
<center><button id="btn1" class="btn btn-primary"> Calculate</button>
<button id="btn2" class="btn btn-primary"> Show</button>
<button id="btn3" class="btn btn-primary"> Sort</button>
<button id="btn4" class="btn btn-primary"> Clean</button></center>
</body>
But still have an issue showing the result in the other container

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>

Categories