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";
}
}
Related
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
I have a multi selectable telerik RadComboBox component on my page. I'm using an "OnClientDropDownClosed" client side event. I do post back manually, not automatic. What i want is, when the dropdown closed, i want to compare the old checked items with the new checked items on client side. How can i get the old checked items and the new checked items via javascript?
I found the solution. I keep the old selected IdList. On rad combo box closed function, i compare the two lists.
var oldSelectedIdList = [];
function radComboBoxSelectedIdList() {
var selectedIdList = [];
var combo = $find("<%= RadComboBox.ClientID %>");
var items = combo.get_items();
var checkedIndices = items._parent._checkedIndices;
var checkedIndicesCount= checkedIndices.length;
for (var itemIndex = 0; itemIndex < checkedIndicesCount; itemIndex++){
var item = items.getItem(checkedIndices[itemIndex]);
selectedIdList.push(item._properties._data.value);
}
return selectedIdList;
}
$(document).ready(function () {
oldSelectedIdList = radComboBoxSelectedIdList();
});
function areThereAnyChangesAtTheSelection()
{
var selectedIdList = radComboBoxSelectedIdList();
var isTheCountOfEachSelectionEqual = (selectedIdList.length == oldSelectedIdList.length);
if(isTheCountOfEachSelectionEqual == false)
return true;
var oldIdListMINUSNewIdList = $(oldSelectedIdList).not(selectedIdList).get();
var newIdListMINUSOldIdList= $(selectedIdList).not(oldSelectedIdList).get();
if (oldIdListMINUSNewIdList.length != 0 || newIdListMINUSOldIdList.length != 0)
return true;
return false;
}
function onRadComboBoxClosed(sender, args) {
if (areThereAnyChangesAtTheSelection())
//Your Code Here
}
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.
Im new to javascript and coding in general, I'm trying to make a simple to do list but cant get the delete button to delete all the checkboxes, it will only delete the last checkbox made. Thanks guys
http://jsfiddle.net/2L8y73ac/
var task = document.getElementById('textinput');
function ObjectTask() {
self = this;
self.init = function() {
self.itemText=document.createTextNode(task.value);
self.checkbox = document.createElement("input");
self.checkbox.type = "checkbox";
self.checkbox.name = task.value;
self.checkbox.id = "checkbox";
self.checkbox.value = "0";
self.checkbox.onclick = self.clickMe;
self.listItem=document.createElement("li");
self.listItem.id = task.value;
self.listItem.appendChild(self.itemText);
self.listItem.appendChild(self.checkbox);
self.deleteCheckBox = document.getElementById('deleteBtn');
self.deleteCheckBox.onclick = self.deleteMe;
document.getElementById('place').appendChild(self.listItem);
}
self.clickMe = function() {
if (self.checkbox.value === "0") {
self.checkbox.value = "1";
console.log("1");
}else {
self.checkbox.value = "0";
console.log("0");
}
}
self.deleteMe = function(){
if (self.checkbox.value == "1"){
var parent = self.listItem.parentNode;
parent.removeChild(self.listItem);
}
}
}
function taskadd() {
var taskNew = new ObjectTask();
taskNew.init();
}
I can't seem to get the adding to work either, but that doesn't matter. :)
The problem is that you assign a new click handler to the single delete button everytime when you add an item. When you click the delete button, the event handler of the last item is called, everytime (even when the item itself is already deleted).
The problem is in this piece of code:
self.deleteCheckBox = document.getElementById('deleteBtn');
self.deleteCheckBox.onclick = self.deleteMe;
deleteCheckBox is assigned the (global) delete button. After that, you assign a new onclick handler to it, overwriting the previous one.
A better approach would be to write one generic handler for the delete button, which looks up all selected checkboxes and finds the other elements belonging to it to delete them. So just like your global taskadd(), you should also have a global taskdelete() that deletes all selected tasks.
I am trying to remove an object and store it (in case a user wants to retrieve it later). I have tried storing the object in a variable like it says in the thread below:
How to I undo .detach()?
But the detach() does not remove the element from the DOM or store it. I am also not getting any error messages. Here is the code I am using to detach the element:
function MMtoggle(IDnum) {
var rowID = "row" + IDnum;
var jRow = '#' + rowID;
thisMMbtn = $(jRow).find(".addMMbtn");
var light = false;
var that = this;
if (light == false) {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
$(this).unbind("click");
light = true;
}
);
}
else {
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
thisMM = thisRow.find(".mmCell");
SC[rowID].rcbin = thisMM.detach(); //here is where I detach the div and store it in an object
$(this).unbind("click");
light = false;
}
);
}
}
MMtoggle(g.num);
A fiddle of the problem is here: http://jsfiddle.net/pScJc/
(the button that detaches is the '+' button on the right. It is supposed to add a div and then detach it when clicked again.)
Looking at your code I don't think so you need detach for what you are trying to achieve.
Instead try this code.
thisMMbtn.bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var $mmCell = thisTxt.find('.mmCell');
if($mmCell.length == 0){
$mmCell = $('<div class = "mmCell prep"></div>')
.appendTo(thisTxt).hide();
}
$mmCell.toggle();
//$(this).unbind("click");
}
);
Demo