How to keep the checkbox status after refreshing the page - javascript

I already looked at the other threads but couldn't find anything.
I have one checkbox which hides some table columns by changing it's status but after every refresh it changes to the initial status (checked) and the columns aren't hidden anymore.
Is there any way to keep the status after the refresh? Can I apply local storage in this case and is there a way to do it without jQuery?
Below is some code:
EDIT: added the suggested function for localstorage
<script type="text/javascript">
function hide_show_table(col_name)
{
var checkbox_val=document.getElementById(col_name).value;
if(checkbox_val=="hide")
{
var all_col=document.getElementsByClassName(col_name);
for(var i=0;i<all_col.length;i++)
{
all_col[i].style.display="none";
}
document.getElementById(col_name+"_head").style.display="none";
document.getElementById(col_name).value="show";
}
else
{
var all_col=document.getElementsByClassName(col_name);
for(var i=0;i<all_col.length;i++)
{
all_col[i].style.display="table-cell";
}
document.getElementById(col_name+"_head").style.display="table-cell";
document.getElementById(col_name).value="hide";
}
}
</script>
<script>
window.onload = function() {
const checkbox = document.getElementById('fdt_col');
checkbox.checked = !!localStorage.getItem('checked');
checkbox.addEventListener('change', function(){
localStorage.setItem('checked', this.checked);});
}
</script>
echo"<input type='checkbox' name='fdt_col' value='hide' id='fdt_col'
onchange='hide_show_table(this.id);' checked>some text</input><br/>";
Thank you

I see you're using Vanilla javascript so you can use the localStorage like so:
window.onload = function() {
const checkbox = document.getElementById('fdt_col');
checkbox.checked = !!localStorage.getItem('checked');
checkbox.addEventListener('change', function() {localStorage.setItem('checked', this.checked);});
}
Note about localStorage vs sessionStorage
localStorage will save your items on all tabs while sessionStorage is to be used if you need separation between tabs

Related

JavaScript conditions for checkbox OnLoad

I have a checkbox which determines whether to hide or make elements visible. My question: is there a way to also include if the checkbox was originally unchecked on page-load to permanently remove those elements so they can't be recalled, otherwise continue what is currently below? Hope that makes sense.
function myEmail() {
var emailBox = document.getElementById("checkemail");
var emailradios = document.getElementById("emailradios");
var emailOptOutSix = document.getElementById("emailOptOutSix");
var emailOptOutForever = document.getElementById("emailOptOutForever");
if (emailBox.checked == true){
emailradios.style.visibility = "hidden";
emailforever.style.visibility = "hidden";
emailOptOutSix.checked = false;
emailOptOutForever.checked = false;
} else {
emailradios.style.visibility = "visible";
emailforever.style.visibility = "visible";
}
}
Its a little unclear what your asking. If you want to delete the items when the checkbox is unchecked (on page load) then you could do this:
Here is a working version JSFiddle
It should be noted, that getting the cookie using substring is not the best practice. It would be wise to create a function that handles this. An example can be found here. Working with cookies
//gets the cookie for checked/not checked state
var checked = document.cookie;
//On window load
window.onload = function() {
//Get the value of the cookie
var emailBoxChecked = checked.substring(checked.indexOf("=") + 1);
if (emailBoxChecked == "checked"){
//set the state of the checkbox to true
document.getElementById("emailbox").checked = true
//If checked do something
} else {
//set the state of the checkbox to false
document.getElementById("emailbox").checked = false
//remove radio buttons that are contained within the emailRadios div
var parent = document.getElementById("myForm")
var child = document.getElementById("emailRadios")
parent.removeChild(child)
}
};
//Call this function when the checkbox is clicked
var emailChecked = function () {
var emailBoxChecked = document.getElementById("emailbox").checked
if (emailBoxChecked){
// store the state of the checkbox as checked in a cookie
document.cookie = "email=checked";
} else {
// store the state of the checkbox as NOT checked in a cookie
document.cookie = "email=unchecked";
}
}

Change image of button when pressed, using javascript

I am trying to set a value in variable when a specific button is pressed. I want this button to be in pressed state when i again reload the page. I am trying to check the value of variable in pageloaded function but i don't know that how can change the state of button in javascript. Pls help
HTML:
<button onclick="changeit()"><img src="bla.jpg" id="changevalue"></button>
JS:
function changeit(){
document.getElementById("changevalue").src = "newimg.jpg";
}
HTML:
<button id="myButton"><img src="myImage.jpg" id="myImage"></button>
JS:
var NEW_IMAGE_URI = "myNewImage.jpg";
var buttonState = false;
function changeButtonImage(){
if (buttonState) {
return;
}
document.querySelector("#myImage").src = NEW_IMAGE_URI;
buttonState = true;
}
document.addEventListener("DOMContentLoaded", function(event) {
var buttonElement = document.querySelector('#myButton');
buttonElement.addEventListener('click',changeButtonImage);
});

How to save the checkbox state even after the page refresh?

I have multiple checkboxes on my UI which when checked doing some operation. But the moment I refresh the page all the check boxes are unchecked again. How can I use AJS.Cookie (Atlassian Javascript framework) to save the state. Source Code which I have written but it gives the cookie value as undefined.
'#generate-canvas-button' is the id of the button which passes all the checked checkboxes.
// Wait until the page is completely loaded.
AJS.$(document).ready(function() {
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking saved cookie.
if (AJS.Cookie.read(name)) {
// Updating checkbox state.
$(this).prop('checked', true);
}
});
// Clicking the OK button should run submit(), pop up displays all checked boxes
$('#generate-canvas-button').click(submit);
});
function submit() {
var checked = [];
var targetGroupActors = [];
var bigPictureActors = [];
var bigPictureImpacts = [];
var productDetailsActors = [];
var productDetailsDeliverable = [];
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking checkbox state.
if ($(this).is(":checked")) {
// Saving checkbox name to cookie.
AJS.Cookie.save(name, true);
} else {
// Remove checkbox state from cookie.
AJS.Cookie.erase(name);
}
if ($(this).is(":checked")) {
impactMapValues = $( this ).prop('id');
impactMapActor = $( this ).prop('name');
var value = document.getElementById(impactMapValues).value;
if (impactMapActor == "actor-checkbox") {
targetGroupActors.push(value);
}
if (impactMapActor == "impact-checkbox") {
var result = value.split(",");
actor_value = result[0];
impact_value = result[1];
bigPictureActors.push(actor_value);
bigPictureImpacts.push(impact_value);
}
if (impactMapActor == "deliverable-checkbox") {
var result = value.split(",");
actor_value = result[0];
deliverable_value = result[1];
productDetailsActors.push(actor_value);
productDetailsDeliverable.push(deliverable_value);
}
checked.push(value);
}
});
addTotargetGroup(targetGroupActors);
addToBigPicture(bigPictureActors,bigPictureImpacts);
addReleaseTarget(productDetailsActors,productDetailsDeliverable);
}
Try this approach:
// Wait until the page is completely loaded.
$(document).ready(function() {
// Iterating over all checkboxes on page.
$('input:checkbox').each(function() {
// Getting checkbox name.
var name = $(this).attr('name');
// Checking saved cookie.
if (AJS.Cookie.read(name)) {
// Updating checkbox state.
$(this).prop('checked', true);
}
// Attaching onchange handler.
$(this).change(function() {
// Checking checkbox state.
if ($(this).is(":checked")) {
// Saving checkbox name to cookie.
AJS.Cookie.save(name, true);
} else {
// Remove checkbox state from cookie.
AJS.Cookie.erase(name);
}
});
});
});
Use viewstate concept intead of using other cookies logic
Wrap all your logic in
AJS.toInit(function ($) {
// You can use $ instead of AJS.$ here
...
});
This is Atlassian's equivalent of $(document).ready(...) which allows all the Atlassian code to load before you call yours.

javascript slider gets reset if I navigate to the second page

I have a javascript function which dynamically updates the page content based on the UI slider values that I am selecting. This is the javascript function.
<script>
var masterData=[];
$(function() {
$("button").on('click',function(){ loadXMLDoc(); });
$("[data-slider]")
.each(function (index) {
var range;
var input = $(this);
$("<span>").addClass("output").attr("id","output"+index)
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
</script>
However, the problem is if I navigate to the second page, the slider gets reset. Also, the function selects the values based on the UI slider only for the page that am currently in. Is there any way to modify it? Probably, if you take a look at this, you can understand the problem that am mentioning.

Dynamically created buttons not firing onclick event

Thanks in advance for any help I can get with this one. I'm working on a project which requires me to create buttons out of select options. The buttons are being created without issue, but I can't figure out for the life of me why the onclick trigger isn't firing. I've recoded this in jQuery too and am having the same issue. I'll post both.
JS (with a bit of JS):
var buttonObj = {
addButtons: function() {
$('select').each( function() {
// Check that buttons don't already exist
var selectBox = $(this);
if(!selectBox.parent().next().hasClass('button-group')) {
// Create button div
var buttonGroup = document.createElement('div');
buttonGroup.className = 'button-group';
// Check which type of button to create
var buttonLen = selectBox.children().length;
if(buttonLen > 3) {
// Long button classes
var buttonClass = 'decision-button long';
} else {
// Short button classes
var buttonClass = 'decision-button';
}
selectBox.parent().parent().append(buttonGroup);
// Create Buttons
for(var i = 1; i < buttonLen; i++) {
var newButton = document.createElement('button');
newButton.className = buttonClass;
newButton.type = "button";
newButton.innerHTML = selectBox.children().eq(i).html();
buttonGroup.appendChild(newButton);
newButton.onclick = function() {
alert($(this));
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
}
}
} else {
console.log('do nothing');
}
});
}
}
buttonObj.addButtons();
The Answer
I wasn't checking for $(document).ready() because I was lead to believe that if you're loading the JS at the bottom of the DOM, it is unnecessary. In this case, it was totally necessary.
Thanks to all those who helped.
I think jQuery got an easy way to bind dynamically elements.
jQuery provides .on() (or .live() for older version) for this.
Example:
jQuery(document).ready(function(){
var btnClass=".someClass";
$(document).on('click',btnClass,function(e){
alert($(this));
$(this).siblings().removeClass('selected');
$(this).addClass('selected');
});
});

Categories

Resources