Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign the same random ID to three different keys

I have an ID generator. I would like the same ID to be assigned to 3 different keys in local-storage. Here is my code:

var ID = function () {
  return "_" + Math.random().toString(36).substr(2, 9);
};

let user_name = document.getElementById("username");
let user_paswrd = document.getElementById("password");
let user_email = document.getElementById("email");

let store_data = () => {
  let i = 0;
  let input_username = localStorage.setItem(
    "username_nr" + ID(),
    user_name.value
  );
  let input_password = localStorage.setItem(
    "password" + ID(),
    user_paswrd.value
  );
  let input_email = localStorage.setItem("email" + ID(), user_email.value);
};

Now the generator assigns 3 different IDs to the keys "username", "password" and "email". How can I change this so that the generator assigns the same ID to the keys?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Rather than calling ID 3 times, each time generating a new ID, call it a single time and use the same value in each place that it’s needed:

let store_data = () => {
  let id = ID();
  let i = 0;
  let input_username = localStorage.setItem(
    "username_nr" + id,
    user_name.value
  );
  let input_password = localStorage.setItem(
    "password" + id,
    user_paswrd.value
  );
  let input_email = localStorage.setItem("email" + id, user_email.value);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading