Checkbox not printing after restoring values from localstorage - javascript

We have some checkboxes in our code when selecting checkbox and executing window.print(), checked boxes is displayed. But when we reset items and Restore again and after that if we execute window.print() selected checkboxes are not displayed.
Here is code for storing checkbox into localstorage
$('input[type="checkbox"]').each(function() {
let id = $(this).attr('id');
var checkbox = document.getElementById(id);
localStorage.setItem(id, checkbox.checked);
});
Get checkbox values from localstorage
$('input[type="checkbox"]').each(function() {
let id=$(this).attr('id');
var checked = JSON.parse(localStorage.getItem(id));
document.getElementById(id).checked = checked;
});

Related

Iterate over checkboxes array to determine if checked

I have a table with a "select all" checkbox. When I populate this table, all of the items that have been selected previously are checked. Currently, the "select all" checkbox will return checked even if not all of items are checked. I'm trying to create a function that will iterate over each checkbox, and if all are checked, then it will automatically toggle the select all checkbox. Same logic if not all items are selected - the select all checkbox will not be selected.
Here's the code I have so far:
function unclickSelectAll(parent) {
var $checkboxes = parent.find('input[type="checkbox"]');
var $selectAllCheckbox = $checkboxes.filter('.vendor');
var $invoiceCheckBoxes = $checkboxes.filter('.invoice');
$invoiceCheckBoxes.each(function(i, c) {
var checkbox = $(this);
if (checkbox[i].checked) {
$selectAllCheckbox.prop('checked', true);
} else {
$selectAllCheckbox.prop('checked', false);
}
});
};
What happens currently is that it will loop over the first checkbox, and if it's checked it will change the checked property of the select all check box to true. Then through the next loop I get an error that it cannot find the 'checked' property of checkbox[i];
you can do something like
$('.invoice:checkbox').click(function () {
unclickSelectAll();
});
function unclickSelectAll() {
var allSelected = $('.invoice:checked:checkbox').length === $('.invoice:checkbox').length;
$('.vendor:checkbox').prop('checked', allSelected);
}
plunker: http://plnkr.co/edit/iSrpfjd4Z7FUIhQkewcF?p=preview
You're switching the state of the select-all checkbox after testing each checkbox, so the final state will just be based on the last checkbox. You need to test whether all the checkboxes are checked. You can do this by simply counting the number of checkboxes and the number of checked checkboxes; if the count is the same, they're all checked.
if (parent.find(':checkbox').length == parent.find(':checkbox:checked').length) {
$selectallCheckbox.prop('checked', true);
} else {
$selectallCheckbox.prop('checked', false);
}

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');
});

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.

how to check all checkboxes and keep them checked through pagination

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.

How to implement a click event on mutually exclusive checkboxes in jQuery?

I have two checkboxes:
<input id="outside" type="checkbox" value="1" data-gid="41820122" />
<input id="inside" type="checkbox" value="1" data-gid="41820122" />
I've made them mutually exclusive with:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
});
});
This works fine. But I also want to add additional click functionality to the 'inside' checkbox. I want it to enable/disable a textarea on the same form, so I've done this:
$('#application_inside').click(function() {
if ($(this).is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
});
So, if the 'inside' checkbox is checked, the textarea will be enabled, if it's not checked, the textarea should be disabled.
The problem is that if the 'inside' checkbox is checked, and the user then checks the 'outside' checkbox, the 'inside' becomes unchecked (as it should be), but the textarea remains enabled. This appears to be because the 'inside' checkbox was never actually clicked by the user.
I've tried working around this with the following:
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
checkboxes.triggerHandler("click"); //new code to fire any click code associated with unchecked boxes
});
});
But this just throws the browser in a loop, since the two different click events end up calling each other.
How can I keep my mutually exclusive code while still allowing the enable/disable code for the 'inside' checkbox to work?
You can create a custom event that you trigger when you click on #application_inside. Also you will fire this custom event when you uncheck other boxes because of the exclusiveness.
Here is an example: http://jsfiddle.net/gs78t/2/
you may try something like this
var insideChanged = function() {
if ($('#inside').is(':checked')) {
return $('textarea').removeAttr('disabled');
} else {
return $('textarea').attr('disabled', 'disabled');
}
};
$('#application_inside').click(insideChanged);
$(function(){
//mutually exclusive checkboxes
$("input[data-gid]").click(function(){
var gid = $(this).attr('data-gid');
var fid = $(this).attr('id');
var checkboxes = $("input[data-gid=" + gid + "][id!=" + fid + "]");
checkboxes.attr("checked", false);
insideChanged(); //new code to fire any click code associated with unchecked boxes
});
});

Categories

Resources