How do you save a Checkbox State in localStorage - javascript

I'm designing a web app for Document Managers, and there is a 'settings' page, where the user sees a pair of checkboxes formatted to look like the iphone toggle buttons. they work and all, but whenever the user leaves the website or refreshes the page the state of those buttons is reset back to the default. is there a way to save the state of them using localStorage or do i need to use cookies? EDIT in the JavaScript file (code shown below) there are two functions, one called saveSettings and the other loadSettings, but if i have to do it all in one function then please tell me. END OF EDIT any help at all would be greatly appreciates. so far i have;
localStorage.CheckboxName = $('#CheckboxName').val();
to save the checkbox to localStorage and;
$('#CheckboxName').val(localStorage.CheckboxName);
but it won't save. Am i doing something wrong?
EDIT
here's the HTML code of the two checkboxes;
<li style = 'color: #FFFFFF;'>Notifications<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'notifications' id = 'notifications' /></span></li>
<li style = 'color: #FFFFFF;'>Preview<span class = 'toggle'><input type = 'checkbox' class = 'toggle' name = 'preview' id = 'preview' checked = "true" /></span></li>
END OF EDIT
Any help would be amazing, thanks in advance x

I'm not sure, but I've always believed that it was like this :
window.localStorage.setItem('CheckboxName', $('#CheckboxName').val());
$('#CheckboxName').val(window.localStorage.getItem('CheckboxName'));

You could try the following
$("#CheckboxName").is(':checked')?'checked':'not' and save the output, seems to be what is suggested here:
How to use local storage to retain checkbox states for filtering items

To store an Item just remember that the store only holds strings.
Eg.
var val = $('#CheckboxName').val();
window.localStorage.setItem(key, JSON.stringify(val));
So when you read the value back you need to deserialize the string.
var str = window.localStorage.getItem(key);
var obj = $.parseJSON(str);
Or you could just do string comparison whatever suites your needs better in your case what I would do is store an object of id value pairs in one storage key and deserialize them all to work with proper object
Eg.
var val = {
CheckboxName1: true,
CheckboxName2: false,
CheckboxName3: false, // ect....
};
window.localStorage.setItem(key, JSON.stringify(val));

Related

How to get method that changes name in javascript

I am making a script that changes settings on twitch.tv
When I need to check if a toggle button is checked, this is simple enough. But the method name to catch the true, false value on the .checked, changes every time I load the page.
var latencyButton = document.getElementsByClassName("tw-toggle__input")[0];
if(latencyButton.__reactEventHandlers$kupq2smnamk.checked)
latencyButton.click();
console.log("Latency Changed");
}
It's the __reactEventHandlers$(This part) that changes so I have something to start off on.
Edit: added the HTML that surrounds the toggle button
<div data-test-selector="low-latency-toggle" class="tw-align-items-center tw-flex"><label class="tw-drop-down-menu-input-item__label tw-flex-grow-1 tw-mg-r-2" for="f8960cb3c79352dd6dd718358e42a812">Low Latency</label><div class="tw-toggle" data-test-selector="low-latency-toggle"><input type="checkbox" class="tw-toggle__input" id="f8960cb3c79352dd6dd718358e42a812" data-a-target="tw-toggle"><label for="f8960cb3c79352dd6dd718358e42a812" class="tw-toggle__button"><p class="tw-hide-accessible">Low Latency</p></label></div></div>
Is there a way to get the checked value without the name of the method? or like a way to get the method name to use in a variable?
Thanks for you time
-Crysal
You could maybe try using filter and indexOf to find the function name. Something like:
let el = document.querySelector(".tw-toggle__input");
let reactHandlerName = Object.keys(el).filter((item) => item.indexOf('__reactEventHandlers')>=0);
let reactHandler = el[reactHandlerName[0]]; // this should be the function name

how to save data through javascript in select list in crm

I am adding a selectlist in my web resource and then saving the data through JavaScript like this
entity.attributes['new_category'] = categoryValue;
where 
categoryValue = $("#category option:selected")[0].innerHTML
But when i am creating the entity like 
XrmServiceToolkit.Soap.Create(entity)
it is throwing me and error
When trying to assign option set values using XrmServiceToolkit, which new_category does look like it is, you need to assign the value like so:
entity.attributes["new_category"] = { value: categoryValue, type: "OptionSetValue" };

Xrm.Utility.openEntityForm setting Look Up field

I am attempting to use the Xrm.Utility.openEntityForm() method to open a new custom entity form and programatically set an entity look up field. I am following an example on http://msdn.microsoft.com/en-us/library/gg334375.aspx very closely but getting nondescript error. Any help with actually setting the field or possibly finding the logs for the error would be appreciated.
The code example I am following.
function OpenNewContact() {
var parameters = {};
//Set the Parent Customer field value to “Contoso”.
parameters["parentcustomerid"] = "2878282E-94D6-E111-9B1D-00155D9D700B";
parameters["parentcustomeridname"] = "Contoso";
parameters["parentcustomeridtype"] = "account";
//Set the Address Type to “Primary”.
parameters["address1_addresstypecode"] = "3";
//Set text in the Description field.
parameters["description"] = "Default values for this record were set programmatically.";
//Set Do not allow E-mails to "Do Not Allow".
parameters["donotemail"] = "1";
// Open the window.
Xrm.Utility.openEntityForm("contact", null, parameters);
}
The function I have created to do the same with my custom entity is as follows :
function createNewService() {
var locationId = trimBrackets(Xrm.Page.data.entity.getId());
var primaryField = Xrm.Page.data.entity.getPrimaryAttributeValue();
var entityLogicalName = Xrm.Page.data.entity.getEntityName();
var parameters = {
cw_location: locationId,
cw_locationname: primaryField,
cw_locationtype: entityLogicalName
};
Xrm.Utility.openEntityForm("cw_service", null, parameters);
}
the name of the entity I am opening a form work = cw_service (this isn't the problem as I can open a blank form with Xrm.Utility.openEntityForm("cw_service");)
the name of the field I am trying to set is cw_location.
I'd post a picture of the error message but I don't have the reputation yet to do that.
For simple lookups you must set the value and the text to display in the lookup. Use the suffix “name” with the name of the attribute to set the value for the text.
Don’t use any other arguments for simple lookups.
For customer and owner lookups you must set the value and the name in the same way you set them for simple lookups. In addition you must use the suffix “type” to specify the type of entity. Allowable values are account, contact, systemuser, and team.
For your example, it is a simple lookup, I suppose. So, Please try using the code below:
var parameters = {
cw_location: locationId,
cw_locationname: primaryField
};
For more information, Please visit Set the value for lookup fields.

Dynamic key names in object list

I currently have a 'meta' modal box using bootstrap and angularjs, however I want to use this to now save some entered details and post this to the web API sitting behind. This all works fine and happily, however because it is a 'meta' modal, which will be used for all of the different entering methods this means I will need to dynamically create the key of the posted data, i.e.:
var dataSender = [{ ID: $scope.iUserItem, ClientName: userItem.Name }];
ClientName is the item that will need to be dynamically changed each time. Is there a way to pass a variable into this section or will I have to write a different post for each 'meta' data being sent?
Create your object seperately.
var myObj = {};
var ClientName = "FirstCape";
myObj[ClientName] = "data" // { "FirstCape" : "data"};
var dataSender = [myObj];

I'm getting a "newItem() was not passed an identity for the new item" error while trying to add a new item to a JSON store

I've seen other posts in this site regarding the same issue and I've tried the solutions given. I've also visited the links that may offer a solution but I'm still stuck with the same error.
I'm using DOJO and something as simple as this won't even work
myStore.newItem({id: 'test', otherfield: 'otherinfohere'});
myStore.save();
Supposedly the "newItem() was not passed an identity for the new item" error appears when you haven't provided an identifier for the new item, which i have.
The whole purpose of this (Just in case anyone can provide a good idea or has done something similar before) is that i want to create a data grid that shows info from a particular store. The problem is, that in that store all the items may not have the same structure. For instance:
I may have a store that looks like this
{identifier: 'id',
label: 'name',
items: [
{ id:'1', name:'Ecuador', capital:'Quito' },
{ id:'2', name:'Egypt', capital:'Cairo' },
{ id:'3', name:'El Salvador', capital:'San Salvador' , additionalField: 'otherinfohere'},
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo', additionalField: 'otherinfohere'},
]}
This is possible because I'm the one constructing the store in a Spring Controller (I'm also using the Spring Framework) from information I have locally stored in a Berkeley DB. So what i need is a data grid with a dynamic layout because I don't want blank spaces to show in the view in the rows with lesser amount of fields, and i need to show all the info in the store at the same time, but i don't know how to do this.
I thought of doing it by creating a simple layout of only 1 field. In it I would load data from a store i create dynamically at runtime. The data in the store would be composed of HTML combined with the values coming from the original store so I could obtain something like this, which is inside an attribute of a JavaScript Object and let the browser parse it for me:
<div><span>id: originalID </span>....</div>
This of course is a simple example, the html layout i'm looking for is far more complicated, but i think that passing it as a string to an object might do the trick.
The problem is that i don't even know if that idea will work because i get that error whenever i try to add values to my secondary store.
rdb.modules.monitor.historicStore.fetch({onComplete: function(items, request){
for (var i = 0; i < items.length; i++){
var item = items[i];
var obj = new Object();
obj.id = rdb.modules.monitor.historicStore.getValue(item, "id");;
var html = "<div><span>";
html += rdb.modules.monitor.historicStore.getValue(item, "sql");
html += "</span></div>";
obj.html = html;
myStore.store.newItem(obj);
}
}});
In this context "historicStore" refers to the JSON store that has the values that i need to convert and add to "myStore" after i added some HTML.
I hope you got the main idea of what I'm trying to do. If anyone can help me we either of these problems i would really appreciate it. Thanks in advance
For the issue regarding store:-
"id" is mandatory for a store, if it is going to be used for a grid(datagrid, EnhancedGrid, etc. whatever). The items are handled only on basis of "id" attribute by the grid data structures.
Usually, id can be a loop variable/ auto incrementation, to avoid any cases like you have said. Before adding the store to the grid, ensure that all items have the id attribute. You can write a function which will loop through each item and check for this, else add an auto-incrementing value for the id attribute of that item.

Categories

Resources