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

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

Related

How to uncheck the checkbox of a jquery table when changing a combobox?

I have the following question, when I change the value of the combobox, the checkboxes are still marked, with prop the values are unmarked, but this time it does not work, the idea is to reset the marked checkboxes when the value of the checkbox is changed.
Regards.
var cambio = $("#cmbKit").on('change', function () {
var checkPoint = !$(this).data('checked');
$('#tblCajas input[type="checkbox"]').each(function () {
if (checkPoint == true) {
$(':checkbox').prop('checked', false);
$("input[type='checkbox']").prop('checked', false);
}
});
});
if (cambio) {
selectedBox = 0;
$('#divCalculos').hide();
$('#btnPlanificar').hide();
}
As you want to reset every checkbox on change event of combobox, you can use below code -
$("#cmbKit").change(function() {
$("input[type='checkbox']").prop('checked', false);
});
You shouldn't use any if condition as you are going to reset it after every change event.
Please note that given code will reset all checkboxes on page, add table selector as well in case you have multiple table with different content.
Hope this helps.

First on-click on checkbox displays modal popup window. How can i make on-second-click unchecks the checkbox?

I am doing a popup window using Bootstrap modal that is triggered by the click of a checkbox in the main page. The popup window contains several textboxes for searching from the database based on user's input. Then after the input and the click of a search button, a table will display the data retrieved on the same popup window. Then, after the user chooses a row from the table, the chosen data will be displayed in their respective textboxes in the main page and the checkbox will be checked.
My plan is to uncheck the checkbox on a second click (thinking if the user suddenly decided to cancel their decision - checking the checkbox). I tried but it didn't uncheck the checkbox. Instead, the popup window comes out at every click of the checkbox and the checkbox won't uncheck anymore.
$('#inputNew').on('hidden.bs.modal', function (e) {
document.getElementById("inputNewCheckbox").checked = true;
document.getElementById("inputMother").style.display = 'block';
document.getElementById("inputMotherlabel").style.display = 'block';
var value = $('#myPopupInput1').val();
$('#inputMother').val(value);
$('#inputNew').modal('hide');
});
$('#inputNew').on('click', '#SearchMother', function () {
var value = $('#myPopupInput1').val();
$('#inputMother').val(value);
$('#inputNew').modal('hide');
});
if ($checkbox.data('waschecked') == true && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
$('#inputNewCheckbox').prop('checked', false);
}));
}
This is the checkbox input in the view page:
<input type="checkbox" name="inputNew" value="inputNew" id="inputNewCheckbox" data-toggle="modal" data-target="#inputNew" data-waschecked="false"> New
For the checkbox unchecking part, i also tried
if ($('#inputNewCheckbox').prop('checked', true) && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
document.getElementById("inputNewCheckbox").checked = false;
}));
}
But when i run, the checkbox is checked by default and unchecking doesn't work. Plus the modal popup window appears.
I also tried
if (document.getElementById("inputNewCheckbox").checked = true && $('#inputMother') != '') {
if ($('#inputNewCheckbox').on("click", function () {
document.getElementById("inputNewCheckbox").checked = false;
}));
}
Also same output as above code..can anyone help me out please? How can i fix this?
You're probably better off listening for a change event on the checkbox, and only showing your modal if the checkbox is checked:
$('#inputNewCheckbox').on('change', function(e){
var _this = $(this);
if(_this.is(':checked')){
/* show your modal */
}
});
See change - Event reference and the :checked pseudo-class on MDN.

How to hide or show divs based on checkbox change event

I am trying to show the values based on Checkbox check and uncheck
I have got two checkboxes MNC and Worth (Only the Top Ones), i am trying to show or hide the values based on it (pesent under class pack-panel div)
This is my code
$(document).on('change', '.filtermnc', function() {
$(".pack-panel").each(function () {
var visible = $(this).find('.mnccheckbox').prop('checked')
$(this).toggle(visible);
});
});
$(document).on('change', '.filterworth', function() {
$(".pack-panel").each(function () {
var visible = $(this).find('.worthcheckbox').prop('checked')
$(this).toggle(visible);
});
});
When i tried with this code , it is not working and also it is checking all the correspondng checkboxes
Could you please let me know how to achieve this .
http://jsfiddle.net/F8Vk2/121/
I made for one, but it's just a mater of changing the other one likewise:
$(document).on('change', '.filterworth, .filtermnc', function() {
var $this = $(this),
isChecked = $this.is(':checked'),
$packPanel = $('.pack-panel');
isChecked ? $packPanel.show() : $packPanel.hide()
});
You could use this to get the target of the event and verify if it's checked by .is(':checked'). Also, you don't need to iterate over $('.pack-panel') in order to apply your changes. .toggle() will change the visibility by it's previous one, so I think you should hard code to hide or show the panels.
Change your js to
$(document).on('change', '.filtermnc', function() {
var visible = $(this).prop('checked')
if(visible)
$('.mnccheckbox').closest("li").show();
else
$('.mnccheckbox').closest("li").hide();
});
$(document).on('change', '.filterworth', function() {
var visible = $(this).prop('checked')
if(visible)
$('.worthcheckbox').closest("li").show();
else
$('.worthcheckbox').closest("li").hide();
});
http://jsfiddle.net/F8Vk2/123/
You could try ->
$(document).on('change', '.filtermnc', function() {
$('.mnccheckbox').
closest("li").
toggle($(this).prop('checked'));
});
This is basically finding all with .mccheckbox class, and then toggling based on the property of the checkbox you assigned the event too.

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.

Categories

Resources