Jump to content

Set Identifier value in localStorage


mjsulliv

Recommended Posts

Hello All. I've built a js function to which I pass a checkbox element id. I want this function to set a identifier / value pair in "localStorage".

function storeCheckBoxState(checkBoxID){  checkBoxElement = document.getElementById(checkBoxID);  checkBoxName = checkBoxElement.name;  if (checkBoxElement.checked)	 {	localStorage.checkBoxName="CHECKED";  }  else {	localStorage.checkBoxName="UN-CHECKED";  }}

If I call the function as such:

storeCheckBoxState("dummyCkBx_ID");

I want the identifier added and its value set to the state of the checkbox (check / un-checked) or the value to be updated if the identifier already exists.The issue I'm having problem is that the second part of the "localStorage" identifier (i.e. "checkBoxName") is being interpreted as a literal stirng ("checkBoxName") and not the name value of the check box as returned by the checkBoxElement.name object.How can I do this so I don't have to write a separate function for every checkbox I want to do this for?Thanks --- Mike

Link to comment
Share on other sites

localStorage[checkBoxName]="CHECKED";Dot notation and index notation are equivalent this way.
Excellent, and as always thanks.BTW, do you know if there is any syntactical reason for the dot notation not working this way?--- Mike
Link to comment
Share on other sites

My best guess is to create two kinds of utility. Dot notation unambiguously lets a developer know the name of an identifier without poking around the code. Bracket notation (when the index is a variable, not a literal) requires the developer to look somewhere else to know the name of the identifier. Dot notation requires a developer to hardcode the name of an identifier. Bracket notation allows the code to create/use identifiers dynamically. Both are useful in their own context.

Link to comment
Share on other sites

Also, with dot notation there is no way to use a variable as the name, you only get to use literal names. With array syntax you can use either. So dot notation is fine if you don't need to use dynamic names.

Link to comment
Share on other sites

Also, with dot notation there is no way to use a variable as the name, you only get to use literal names. With array syntax you can use either. So dot notation is fine if you don't need to use dynamic names.
Isn't that what DD just said...:)
Dot notation requires a developer to hardcode the name of an identifier. Bracket notation allows the code to create/use identifiers dynamically.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...