1

I have multiple variables like so

var a0001 = document.getElementById("a0001");
var a0002 = document.getElementById("a0002");
var a0003 = document.getElementById("a0003");

that I use for

a0001.blur= function() {
  localStorage.setItem("a0001", a0001.innerHTML);
};
a0002.blur = function() {
  localStorage.setItem("a0002", a0002.innerHTML);
};
a0003.blur = function() {
  localStorage.setItem("a0003", a0003.innerHTML);
};

My question is I will be working with 100's of variables and I cant figure out how to place a "loop place holder" to process the variables like such (*** represent the place holder that will cycle throw the variables and parse them out)

***.blur= function() {
  localStorage.setItem("***", ***.innerHTML);
};

I am obviously new and this is a single page localstorage project and not sure if I just am not using the right keywords to find the documentation I am looking for or ? so any help will be appreciated.

edit; markup added below

<table>
  <thead>
    <tr>
      <th id="a0001" contenteditable='true' spellcheck="false">ID
      </th><th id="a0002" contenteditable='true' spellcheck="false">First Name
      </th><th id="a0003" contenteditable='true' spellcheck="false">Last Name
  </th></tr></thead>
</table>
  • 1
    Try [this](https://stackoverflow.com/a/42791996/12402732) – Simone Rossaini Jun 14 '21 at 06:34
  • 1
    may be this one: for (let i=0;i<10;i++){ const x = "a000"+i x.blur= function() { localStorage.setItem(x,x.innerHTML); }; } link: https://codeshare.io/pq0wyY – James Jun 14 '21 at 06:38

4 Answers4

0

You can have your variables in an array like const arr = [] then loop through each of them. The entire thing would look something like:

const arr = []

// add variables to array

arr.forEach(a => {
  a.blur = function() {
    localStorage.setItem(a.key, a.innerHTML);
  }
})

You may want to define a unique identifier for the variable, like key or something

Steven
  • 93
  • 2
  • 5
0

Do not need to create multiple variables! Native JS

var elements = document.querySelectorAll('[id^=a000]');

Jquery

$('[id^="a000"]')

Selects elements which IDs start with a000

Tushar Wasson
  • 494
  • 5
  • 10
0

I will suggest two methods to solve this.

  1. Select element by different ids and store in a array Ex:
// Add more id of elements on this array
let selectableElementsId = ['a0001', 'a0002', 'a0003'];

selectableElementsId.forEach(elementId => {
    let element = document.querySelector(`#${elementId}`);
    if(!element) return;
    element.blur = function(){
       localStorage.setItem(element.id, element.innerHTML);
    }
});
  1. add same class to all three or more elements.
// Replace yourClassName with class name of elements
let selectedElements = Array.from(document.querySelectorAll(".yourClassName"));

selectedElements.forEach(element => {
   element.blur = function(){
       localStorage.setItem(element.id || selectedElements.indexOf(element), element.innerHTML);
   }
});
Sparrow
  • 280
  • 1
  • 12
0

The used markup is not entirely clear, but I'm assuming you have a form with some input elements (because blur fires only on form controls and window objets by default).

Despite of the real HTML, you're making a lot of unnecessary work. You've a ton of elements, which you need to handle as a group of elements, not one by one. Using id to identify a group is error prone and also very hard to maintain, and on the top of that, a global variable of each id is created, which floods yet the strongly crowded object with unneeded variables. Also, hundreds of event listeners are not needed, you can use a single listener, which can handle all the elements. Here's a simple code showing how to handle a group of elements:

const form = document.querySelector('#list'),
  storingList = new Map(),
  inputs = form.querySelectorAll('.to-storage');

inputs.forEach((input, idx) => {
  const itemName = 'a' + (idx.toString()).padStart(4, '0');
  storingList.set(input, itemName);
});

form.addEventListener('focusout', e => {
  if (e.target.className !== 'to-storage') {return;} // Quit, not a target element blurred
  const itemName = storingList.get(e.target),
    value = e.target.value;
  console.log(itemName, value);
  // localStorage.setItem(itemName, value); // Commented out to not populate localStorage of SO visitors
});
<form id="list">
  Item 1 <input class="to-storage"><br>
  Item 2 <input class="to-storage"><br>
  Item 3 <input class="to-storage"><br>
  Item 4 <input class="to-storage"><br>
  Item 5 <input class="to-storage"><br>
  Item 6 <input class="to-storage"><br>
  Item 7 <input>
</form>

In the snippet, all the inputs which of values are stored in localStorage, are grouped with a class named to-storage. The grouped inputs and the identifiers are collected to a Map object, hence they're easy to identify in an event handler (Map object can take an element as a key). Notice the dynamic item name creation, which takes care of the running index automatically.

The focusout event listener is delegated (blur doesn't bubble and can't be delegated in a simple way) to the form, which contains all the input elements. This way you can edit and update the HTML of the page, no matter how many inputs needs to be removed or added, you don't have to make any changes to the JavaScript which stores the values.

If your markup is different and you can't apply the snippet, please add an example of your markup to the question.

Teemu
  • 22,918
  • 7
  • 53
  • 106
  • 1
    @JustNoobish619 Does the table contain `td` elements? – Teemu Jun 15 '21 at 04:11
  • Yes they do, thats most of the ids. – JustNoobish619 Jun 15 '21 at 04:36
  • 1
    @JustNoobish619 OK, [here's a fiddle](https://jsfiddle.net/nqojaw8v/2/) showing how the code works with a table. If the table is dynamic, i.e. a user can add/remove rows/cells, then you'd need totally a different approach. Offer a Save button to user, they can click the button when they've finished with the table, and your code should then save the table as an array to `localStorage`. That way it would be much easier to restore the array later. – Teemu Jun 15 '21 at 04:50