how to check all checkboxes and keep them checked through pagination - javascript

I have the scripts below one which checks all checkboxes in a group which works great, and another to pass the checkbox values over the pagination and all works fine the only problem is that when I click the check all box it checks all the pages on page 1 but when I click page 2 only the check all box is checked although the query is working fine. If I click all the checkboxes individually then they pass through the pagination fine, so I don't know why the check all button doesn't. I would like it so that when you click check all, all the boxes stay checked through the pagination as well.
here is my script that checks all checkboxes
<script type="text/javascript">
window.addEvent('domready', function() {
$$('li.head input[type=checkbox]').addEvent('click', function() {
this.getParent('ul').getElements('input[type=checkbox]').setProperty('checked', this.checked);
});
});
</script>
here is the script that remembers the checkboxes
var aa_checkbox;
function init_checkbox(){
//setup blank cb cookie
if(!Cookie.read('cb')){
Cookie.write('cb', JSON.encode({}));
}
//setup "associative array" to match what is currently in the cookie
aa_checkbox = JSON.decode(Cookie.read('cb'));
//set up each checkbox with class="remember_cb"
$$('input.remember_cb').each(function(el){
//mark checked if it is in the cookie
if(aa_checkbox[el.name]){
el.checked = 'checked'
}
//setup onclick event to put checkbox status in the
el.addEvent('click', function(){
if(el.checked){
aa_checkbox[el.name] = 1;
}else{
delete(aa_checkbox[el.name]);
}
})
})
//save aa_checkbox back into cookie upon leaving a page
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};
setup_form();
return true;
}
function setup_form(){
//set up form so that it adds the inputs upon submit.
$$('form.remember_cb_form').each(function(form){
form.addEvent('submit', function(ev){
//clean up previously inserted inputs
var aa_hidden_insert = $$('input.hidden_insert');
$each(aa_hidden_insert, function(el){
el.parentNode.removeChild(el);
})
var el_form = this;
//insert hidden elements representing the values stored in aa_checkbox
$each(aa_checkbox, function(i_value, s_name){
if(i_value){
var el_input = document.createElement('input');
el_input.type = 'hidden';
el_input.value = i_value;
el_input.name = s_name;
el_input.setAttribute('class', 'hidden_insert');
el_form.appendChild(el_input);
}
});
});
});
}
window.addEvent('domready', init_checkbox);
If anyone can help me I would be very greatful, Thanks

It has to do with how your code works. I recommend that the check/un-check should affect the in-memory copy of the backing data. EG if you have an array representing the check boxes, set the check/uncheck in the array then render the array to check/uncheck the corresponding check box. That way, when you check all, all the array cells are set to checked! When you change from page to page, simply read the status of the corresponding array cell.

Related

Show/Hide button based on it's previous state with jQuery

I want to show a button when the user check/uncheck the checkbox. The checkbox can appear checked or unchecked for different users. How can I show/hide a button based on the previous state of the checkbox.
my current code is below.
$('#receive-msg').on('click',function (){
var btnNoMsg = $('#btn-no-msgs');
btnNoMsg.removeClass('hide').addClass('hide');
btnNoMsg.removeClass('hide');
});
I know that I have to store the current state of the checkbox somewhere, and when is clicked again compare the previous state with the current state and show/hide the button.
UPDATE:
I have solved it using the following code.
var btnNoMsg = $('#btn-no-msgs');
var state = $(this).prop('checked');
var receive = $(this).data('receive');
var status = receive ? true : false;
if (state === status){
btnNoMsg.removeClass('hide').addClass('hide');
}else{
btnNoMsg.removeClass('hide');
}
But I'm going to use the code provided by beautifulocoder.
Use a simple toggleClass:
$('#receive-msg').on('click', function () {
$('#btn-no-msgs').toggleClass('hide');
});

pre populate form data on page re load from the session storage

I have a HTML from to capture string data. I am saving those when I hit the save button via ajax. But the scope also includes saving the data on a sessionstorage once I focus out of the form field with the orange save button after it checks the value is not empty. The idea is to pre populate each form field with values stored in the session storage. Everything works fine but I just cant figure out the session storage part. The hard part is how to assign a unique key for each form field, and use that key to find and preload values in the field.
Here is my JS
$('.wrapper').remove()
function renderInput() {
var inputField = '<div class="wrapper"><input class="zoom-text-field" type="text" value=""/><span class="close">save</span></div>';
return inputField;
}
function hideZoomFiled(e, textData) {
$(e).parent().parent().children('.students-name-collection').val(textData);
console.log(textData)
$(e).parent().hide();
$('.students-name-collection').attr('disabled', false);
$(e).prop('disabled', false);
}
function disableInputField(obj) {
$('.students-name-collection').attr('disabled', false);
$(obj).attr('disabled', true);
}
$('.students-name-collection').on('focus', function () {
disableInputField(this);
$(this).next('.wrapper').focus();
$('.wrapper').remove();
$(this).parent().append(renderInput());
var textData = '';
$('.close').on('click', function () {
textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
});
$('.zoom-text-field').on('blur', function(){
if($(this).val() !== ''){
//save the value in the sessionstorage
//This is where I am getting lost
}
});
});
$('#submitForm').on('click', function(){
sessionStorage.clear();
})
// on page load read the session storage and pre fill the form fields
Here is my fiddle
http://jsfiddle.net/sghoush1/ykshgrxg/5/
Here is how you can handle this, as you pointed out the main problem here is how to figure out how to save each input item, and how to place it back when the page loads. What you can do is give each item an index, from 0 to 4.
To get the index of the element you are on, you can add an selected class to it, then use that class in order to find the elements position by using .index($('.selected')), of course we can remove that class when we are done with it. This can be used as the key for the sessionStorage, then the textData is the value:
// Get the index of the input item we are on
$(this).addClass("selected");
var key = $(".students-name-collection").index($('.selected'));
$(this).removeClass("selected");
$('.close').on('click', function () {
var textData = $(this).parent().children().val();
hideZoomFiled(this, textData);
if(!!textData){
//save the value in the sessionstorage
sessionStorage.setItem(key, textData);
}
});
Then for loading them in you can use jQuerys .each and have that on the class .students-name-collection using an index of sessionStorage to give each input the correct value:
// on page load read the session storage and pre fill the form fields
$('.students-name-collection').each(function(index) {
if(sessionStorage[index])
$(this).val(sessionStorage[index])
});
Here is a Fiddle Example

Persisting checked state using localstorage

I have taken the following snippet from a previously asked question on how to store the checked/unchecked status of all checkboxes on a page in localstorage:
$(function(){
var test = localStorage.input === 'true'? true: false;
$('[type="checkbox"]').prop('checked', test || false);
});
$('[type="checkbox"]').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
When I select one of the checkboxes and then refresh the page, once it reloads every single checkbox is checked.
How would I make this store each individual checked state?
Note I may have between 0 - 50 check boxes available depending on how many outstanding records there are in my gridview so I don't have fixed input id's to use only a record id associated to each row.
If you want to rely on a localStorage solution, you may do something like this:
$(function(){
$('[type="checkbox"]').each(function () {
var $this = $(this),
name = $this.attr('name');
$this.prop('checked', localStorage[name] === 'true');
});
});
$('[type="checkbox"]').on('change', function() {
var $this = $(this),
name = $this.attr('name');
localStorage[name] = $this.is(':checked');
});
http://jsfiddle.net/mct7xgq2/
The first part is executed on page load and sets the checked state depending on the localStorage[name] value, where name is the input's name attribute.
The second part executes when any checkbox is being changed: it takes the input's name, as before, but instead of reading the value, it writes it.
IF the page would not load, it would be better to just store the values in JS object rather than using localStorage .
Just create a JS object and keep pushing values inside it and store
Client Side Solution if the page does not reload
$(function(){
var checkedItems ={};
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
checkedItems['id_'+id] = id;
}
});
});
If Page reloads, then your best bet is to use server side concepts like Session.
Send an AJAX request each time a particular checkbox is checked and store it in a session.
SERVER SIDE SOLUTION
$(function(){
$('[type="checkbox"]').on('change', function() {
//Store the ID value also in the localstorage
if($(this).is(':checked')){
var id = $(this).attr('id'); //Get the id if this is checked
$.ajax({
type: 'POST',
url: your server side url path, //store it in a session
data: {'id':id},
dataType: 'html',
success: function(result){
//so some functionality
}
});
}
});
});
Check out the FIDDLE LINK
This is a solution for d3.js with a ternary operator use. It compares the id of this checkbox with the values stored under key=id in localStorage.
If the value is "true" then 'this.checked' is set to 'true', else to 'null' ( null indicates: no 'checked' property)
var box = d3.selectAll(".box").each(function(){
var id = this.id;
var storageValue = localStorage.getItem(id);
this.checked = storageValue === "true" ? true : null;
});
Previously I have setItem in localStorage. The checkbox are created dynamically appended to rows in a table
rows.append('input')
.attr('type','checkbox')
which in turn is based on the data from a cvs. With the following ids for the checkboxes:
.attr("id", function(d,i) { return 'box'+' '+i; })
And the 'change' of the checkbox state:
d3.selectAll(".box").on("change", function() {
var id = this.id;
if ( this.checked ){
localStorage.setItem(id, this.checked);
}
else {
localStorage.removeItem(id);
}
});
I have thousands of rows, each with a checkbox. I did not see a major issue on the timeline inspection. So I guess that this is a good solution. I am not a d3.js expert.

Select All Checkboxes while keeping track of manual selects jquery

I've been using a simple select all script for checkboxes for a while now that looks something like this:
<span id="select">Select All</span>
with
$('#select').click(function(event) {
var $that = $(this);
$('.checkbox').each(function() {
this.checked = $that.is(':checked');
});
});
It's fairly simple. It attaches to an onclick, loops through all the inputs with the class .checkbox and checks or unchecks them accordingly. However what I'd like to do now is make it a bit more user friendly adding the following functionality to it.
1) When the user click the link labeled "Select All" it should select all check boxes as normal, but then change the text to "Deselect All". Similarly, when the user clicks "Deselect All" the text would go back to "Select All".
2) If the users manually select all check boxes I'd like check for this scenario and update the text from Select All to Deselect All as well.
Your code is checking whether a <span> is :checked, which as far as I know is not possible. Perhaps I'm wrong, but in this answer I'll use a different approach to keeping track of that, a data attribute.
// initialize 'checked' property
$('#select').data('checked', false);
// make link control all checkboxes
$('#select').click(function(event) {
var $that = $(this);
var isChecked = ! $that.data('checked');
$that.data('checked', isChecked).html(isChecked ? 'Deselect All' : 'Select All');
$('.checkbox').prop('checked', isChecked);
});
// make checkboxes update link
$('.checkbox').change(function(event) {
var numChecked = $('.checkbox:checked').length;
if (numChecked === 0) {
$('#select').data('checked', false).html('Select All');
} else if (numChecked === $('.checkbox').length) {
$('#select').data('checked', true).html('Deselect All');
}
});
Not jquery, but here's what I'd do
var cb=document.getElementsByClassName('cb'); //get all the checkboxes
var selectAll=document.getElementById('selectAll'); //get select all button
function selectAllState(inputEle,selectAllEle){ //class to manage the states of the checkboxes
var state=1; //1 if button says select all, 0 otherwise;
var num=inputEle.length;
function allChecked(){ //see if all are checked
var x=0;
for(var i=0;i<num;i++){
if(inputEle[i].checked==true){
x+=1;
}
}
return x;
}
function handler(){ //if all checked or all unchecked, change select all button text
var y=allChecked()
if( y==num && state){
selectAllEle.innerHTML='Deselect All';
state=0;
} else if(y==0 && !state){
selectAllEle.innerHTML='Select All';
state=1;
}
}
for(var i=0;i<num;i++){
inputEle[i].addEventListener('change',handler); //listen for changes in checks
}
function checkAll(){ //function checks or unchecks all boxes
for(var i=0;i<num;i++){
inputEle[i].checked=state;
}
handler();
}
selectAll.addEventListener('click',checkAll); //listen for button click
}
var myState=new selectAllState(cb,selectAll); //instance the selectAllState class
This creates a javascript class to manage the states of all your checkboxes. It takes two arguments, the first being the array of checkboxes (which is what you get if you use getElementsByClassName), and the second being the select all button. The internal methods could be exposed using the this keyword if you want to be able to, for example, have a different part of the application select or deselect all the checkboxes.
Try breaking it down in several functions: Let's call the span toggle, as it can select and de-select all.
<span id="toggle">Select All</span>
And we'll have a function to select and de-select all of the values. No need to iterate through the list as prop sets the value for all elements
function SetAll(value){
$(".checkbox").prop("checked", value);
}
Then for the toggle button:
$("#toggle").click(function(){
if($(this).text() == "Select All"){
SetAll(true);
$(this).text("De-select All");
} else {
SetAll(false);
$(this).text("Select All");
}
});
Finally we need an onchange event for each checkbox:
$(".checkbox").change(function(){
var allCheckboxes = $(".checkbox");
var allChecked = $.grep(allCheckboxes, function(n,i){
return $(n).is(":checked");
}); //grep returns all elements in array that match criteria
var allUnchecked = $.grep(allCheckboxes, function(n,i){
return $(n)is(":checked");
},true); //invert=true returns all elements in array that do not match
// check the lengths of the arrays
if (allChecked.length == allCheckboxes.length)
$("#toggle").text("De-select All");
if (allUnchecked.length == allCheckboxes.length)
$("#toggle").text("Select All");
}):

ajax load should remain the status of my checkbox when checked [duplicate]

This question already has an answer here:
checked checkbox will remain through pagination
(1 answer)
Closed 8 years ago.
I have a problem here using .load() ajax/jquery when I use it in pagination. the status of my checkbox will not remain when I go to another page. For example I checked 2 items in page 1 then when I go to page 2 to select another item then when I go back to page 1 to test if my checked item remain checked. unfortunately it became unchecked maybe because of the .load(). Please help me if there is alternative to use aside .load() to remain my checkbox checked.
here is my code for .load() ajax:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');});
$(".paginate_click").click(function (e) {
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active');
return false;
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$('body').on('click', '.paginate_click', function(e){
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
});
</script>
hi #charleshaa it doesnt work this is what i did to my script
and here is my checkbox code
echo "<div id='a'><input type='checkbox' class='tick' name='items[$i]' id='$i' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
What's wrong?? Im badly need help
You need to keep you checked boxes in a variable so you can recheck them after the load.
First add a class to your checkboxes class="tick".
Then you would :
$(".paginate_click").click(function (e) {
// Get all the checked boxes and store their ID in an array
var ticked = [];
$('.tick:checked').each(function(){
ticked.push($(this).attr("id"));
});
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]);
$('.paginate_click').removeClass('active');
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
// Content has loaded but is still raw
// We loop through IDs and check'em
ticked.forEach(function(val, i){
$(val).prop('checked', true);
});
});
$(this).addClass('active');
return false;
});
EDIT:
Also, it is preferable not to use the .click() notation, instead, you should always use .on()
In this example, you would write it like this :
$('body').on('click', '.paginate_click', function(e){
//code
});
It is much better for performance as it only attaches one event listener to body, instead of attaching one to every .paginate_click.
Check my comment about the unique IDs and you should be good to go.

Categories

Resources