Count clicked checkboxes, even after refresh - javascript

I am trying to keep count of how many times the check boxes have been clicked on my site, the check boxes are used for filters (for men, women, age, etc).
At the moment I have this code
jQuery('[id^="checkbox"] input').each(
function (index, element) {
jQuery(this).click(
function () {
console.debug("Hello");
}
);
}
);
Which will count (in console) how many times a check box has been click (with an id starting with checkbox), but because the page refreshes the information (and url) with each click, it will only count the first click, and the rest will not be counted.
Is there anyway to carry on counting after the page has been refreshed?
Thanks

To have a persistent count of all checkboxes being checked across all users, you need to have a central total which all counts update. This will be quite tricky for even large sites like YouTube still struggle with this (although to a lesser extent).
I am unaware that this can be accomplished purely in JS (if anyone knows, please edit this answer) and you will likely need some sort of back-end code.
One approach you could take would be:
update a local total of checked checkboxes on click
set a timer of 1/2 seconds on click
once the timer ends, send an ajax request to a back-end page
back-end page receives the update, update the central total
There are many other approaches you could take. You're likely to run into issues like, the central total might not be very accurate (if ajax requests are interrupted) and your bandwidth usage increasing due to the ajax requests.
Gennady Dogaev shared some really good code which posts the id of the checkbox and it's value to another page. This page would likely have the logic to update a database or something similar to track which checkboxes are being used.
<body>
<input type="checkbox" id="check_1" /> 1
<input type="checkbox" id="check_2" /> 2
<input type="checkbox" id="check_3" /> 3
</body>
$(function(){
$("input[type=checkbox]").click(function(){
var box = $(this);
var data = {
id: box.prop('id'),
checked: box.is(':checked')
};
$.get('https://stackoverflow.com/', data).always(function(response){
console.log('server responded', response);
/*Click registered, do what you want here*/
});
});
});
https://jsfiddle.net/nrLpxLuf/
The below answer was to help count all checked checkboxes on the page and update the total locally. I've left it here for reference.
You don't need to loop over all elements to attach a single click event to all of them.
Instead attach a click event to a collection of checkboxes and then update a total variable from within the click function.
var $inputs = $('[id^="checkbox"] input');
var total = $inputs.filter(':checked').length; //this will be 0 if none are found
$inputs.on('click', function(event) {
if($(this).is(':checked')) {
total++;
} else {
total--;
}
console.log(total);
});
If you only want to see if it has been clicked, just add to the total.

You need to set value on load if you want to count the checked after refresh.
var total = 0;
$(document).ready(function (event) {
//onload count for the checked checkboxes and set total value
total = $('[id^="checkbox"] input:checked').length;
$('[id^="checkbox"] input').on('click', function (event) {
$(this).prop('checked') ? total++ :total--;
});
});

Related

Is there a way to uncheck a checkbox if it's counter equals to 0 with JavaScript or PHP?

help me out on this one if it's possible.
I have a product page and, on this page, people will be able to select a color to remove from the package and select how many items from determined kind they'll buy.
Example: I'm selling blouses and i have'em in 6 colors, red, blue, purple, yellow, orange and green, the customer would be able to choose one between those 6 or none of them and, they must fill some boxes with some infos, like, how many small blouses, or how many large blouses, etc.
But my website will be mainly accessed by old fellas, so, i can't just do my thing and hope for the best like some would, i need to make this site really easy and almost out of the box to use it.
Heres a printscreen of my web page
-> printscreen: http://prntscr.com/ptdyu2
Anyway, i need to uncheck everybox that has a 0 or smaller number in front of it.
Is there a way for doing this?
function(checkbox_validator){
var checkbox0 = document.getElementsByName(tmcp_checkbox_0_0_quantity)
if (checkbox0 != True){
//This is how much i've progressed on this part, only came until this point
}
}
Sure it is possible. I created you a little example. Basically you will add a event listener for change on the input text fields. If the user types a number, or the value will change somehow, the event listener is getting triggered.
Based on the value you will set the specific checkbox checked or unchecked.
var input = document.getElementById('inputItem1');
var checkbox = document.getElementById('checkItem1');
input.addEventListener("input", update);
function update()
{
//Now update the selector
if (input.value > 0 )
{
checkbox.checked = true;
}
else
{
checkbox.checked = false;
}
}
<form>
<input name="input" value="0" id="inputItem1">
<input type="radio" id="checkItem1" name="checkItem1" value="">
</form>

How to show all checked checkboxes also at reloading the page?

I have a problem: my website is searching for checked checkboxes with a javascript.
$(function () {
var $allELements = $('.input-box');
var $selectedElementsListing = $('#selectedElements');
var $selectedElementsLabel = $('#selectedElementsLabel');
var $elementInfo = $('.elementInfo ');
$allELements.on('click', function () {
$selectedElementsListing .html(
$allELements.filter(':checked').map(function (index, checkbox) {
return '<div>' + checkbox.title + '</div>';
}).get().join('')
);
if ($selectedElementsListing .text().trim().length)
{
$selectedElementsListing .show();
$selectedElementsLabel.show();
$elementInfo.show();
}
});
});
So it is searching for checked checkboxes on my main page and is listing the name of the checkboxes on the lower left hand side (as information for the user).
My HTML looks like this:
<div class="elementInfo" >
<p>
<strong id="selectedElementsLabel" ><u>Ausgewählte
Magazine:</u></strong><br />
<span id="selectedElements"></span>
</p>
</div>
And it takes the checkbox names from this input field:
<input class="input-box" title="[[ElementName]]" type="checkbox" id="A[[ID]]" name="ID[]"
value="[[ID]]" checked="[[checked_element]]" />
When I press reload, the information bar for the selected checkboxes isn't appearing. It is showing the checked checkboxes only if I press again any of them (then it shows all which were also selected)
Every time the page is refreshed the DOM is re-rendered and no state is being stored anywhere. To preserve the state of checked boxes you can use localStorage to store the checked state and then upon page load you can read the localStorage and execute a function that checks them by checking local storage data.
// call this every time someone checks a box
window.localStorage.setItem('some key name of data', 'some data structure with checkbox state')
//Do this every time page is loaded
window.localStorage.getItem('previously used key name')
P.S. I assumed you don't have a backend api calling every time someone checks a box where you are preserving state
for further info do visit
A good read to understand state management

jQuery Input checkboxes checked conflict

Something really strange is happening to my checkboxes checked in my table.
I have built an Invoice calculator in a Table, you can see it here and my purpose is that once i check the inputs ( Iva or Irpef) automatically they are not calculated in the Total Amount.
As you can see in the example i have linked, if you check the Irpef Input checkbox, it works well, the Irpef is not calculated in the Total Amount. The problem is that it does not happen the same with my Input Checkbox IVA, why? The code is exactly the same.
When i try just to make them working separately, it's fine, both work well, so it looks like that they can not work together, it might be? What'happening? I need your help on this issue.
thanks
Here the code related to the issue:
function tally(selector) {
var total = 0;
$('p.editable_number').each(function() {
total += parseInt($(this).text()) || 0;
$('#subtotal').html(total);
if($("#iva").is(':checked')){
$('#subtotal').html((total).toFixed(2));
$('#total').html((total*0.00).toFixed(2));
$('#total1').html((total*0.15).toFixed(2));
$('#total2').html((total*0.85).toFixed(2));
}
else {
$('#subtotal').html((total).toFixed(2));
$('#total').html((total*0.21).toFixed(2));
$('#total1').html((total*0.15).toFixed(2));
$('#total2').html((total*1.06).toFixed(2));
}
if($("#irpef").is(':checked')){
$('#subtotal').html((total).toFixed(2));
$('#total').html((total*0.21).toFixed(2));
$('#total1').html((total*0.00).toFixed(2));
$('#total2').html((total*1.21).toFixed(2));
}
else {
$('#subtotal').html((total).toFixed(2))
$('#total').html((total*0.21).toFixed(2));
$('#total1').html((total*0.15).toFixed(2));
$('#total2').html((total*1.06).toFixed(2));
}
})
}
$('#irpef').change(function() {
tally('p#subtotal');
tally('p#total');
});
$('#iva').change(function() {
tally('p#subtotal');
tally('p#total');
});
Try this one, should be fine now. I think you were trying to do an else if and do everything a couple of times instead of once (each function). refreshed
I added variables to keep track of the total/subtotal and vat/irpf.
each() goes through all the p.editable_number elements, so you were executing the same code a couple of times, every time overwriting the previous results, you get the right thing because it's the end loop that counted. Now you are just getting the values once and then calculating the relevant subtotal, vat, irpf and total values(based on the condition of vat or irpf being checked or not).

stuck building a 'cart management' system

I'm trying to build a database for video spots. The main page is a list of spots and you can check them and modify them. What i want to do is build a cart system, where the checked spots' id's are automatically added to the cart and stored as a cookie. That way the use can browse multiple pages while still having everything stay checked.
So far, I have a checkbox on every spot that when checked calls a function that adds the id of the checkbox to an array and stores it as a cookie.
I'm able to retrieve the cookie through jquery. What I need to do is while looping through the spots and printing them, is to check if that spot id is in the cookie, so I can set it as checked or not through php. Is this possible? Is there a better way to accomplish this?
Here is what i have so far.
$(document).ready(function(){
var checkedItems = [];
$('.spotCheck').click(function(){
var currentID = this.id;
checkedItems.push(currentID);
updateCookie();
});
function updateCookie(){
$.cookie('itemList',checkedItems);
}
$('#mainContainer').click(function(){
$('#textInCenter').html($.cookie('itemList') );
});
});
Clicking the checkbox adds the ID to the array checkedItems, and click the mainContainer makes it visible so I can see which items are currently in the array. I can browse through pages and the cookies stay in the array (there's no way to remove them now but I'm not worried about that right now).
So how can I check the array to see if an id is in there when I print the list of spots?
Based on what you're looking for I think that this would work for you:
for (var i = 0; i < checkedItems.length; i++)
{
var elm = $('#' + checkedItems[i]);
if (elm.length > 0)
{
//element with the id exists.
elm.attr('checked', true);
}
}

Javascript tickbox validation

I am trying to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes except the three that were ticked.
How could I go about doing that?
Thanx in advance!
The following will disable the rest of the checkboxes if you select 3 of them, and also enable them once you uncheck one of the three selected..
$(':checkbox').click(
function(){
var selected = $(':checkbox:checked').length;
if (selected == 3)
{
$(':checkbox:not(:checked)').attr('disabled',true);
}
else
{
$(':checkbox:not(:checked)').attr('disabled',false);
}
}
);
Live demo
Have on onclick handler that when a checkbox is clicked it ups a counter by one if it is unchecked it decreases the count. After raising the count, test to see if it is three. Then probably the easiest method is to either save the ids of the three checked boxes or save them in the previous step. Then change the click event to return true only if the ids match the saved ids.
Sorry I don't have time right now to actually write up any code. Hopefully this will get you started.
jQuery
$("#container :checkbox").click(function(){
if ($("#container :checkbox").length >= 3) {
$("#container :checkbox").attr("disabled", "disabled");
}
});

Categories

Resources