how to Insert Multiple Username and Password into localStorage with pure javascript

I try to save every values of the form that I made, username, lastname, email and password, my problem is, how can I push different names and other mentioned above keys to local storage? because the data is being rewrite everytime I save another. please be patient, beginner here, thank you!

const firstName = document.getElementById("firstName");
const lastnName = document.getElementById("lastName");
const email = document.getElementById("newEmail");
const password = document.getElementById("newPassword");

const btnSignup = document.getElementById("btn-signup");

btnSignup.onclick = function () { // when mouse click "signup" button
    const first_name = firstName.value; 
    const last_name = lastName.value;
    const e_mail = newEmail.value;
    const pass_word = newPassword.value;

    if (first_name && last_name && e_mail && pass_word) {
        localStorage.setItem("First Name", first_name);
        localStorage.setItem("Last Name", last_name);
        localStorage.setItem("Email", e_mail);
        localStorage.setItem("Password", pass_word);
    } else {
        alert("Please fill out the forms.");
    }
};

Answer

First and foremost – never store password in local storage and never store in plain text.

You should send it straight to the API, get the token and store it in cookies instead in localstorage.

To store multiple values in local storage you can use JSON.stringify to transform object into string and then store it as a value.

But as I can see you get value from every input separately. I assume that you wrapped whole form in <form> tag so you can just use attribute onsubmit to get whole form as an object just like that https://stackoverflow.com/a/11338832/6599826 and then remove all those document.getElementById... variables.

As you finish that you can just take whole form to JSON.stringify and pass it to localStorage.

localStorage.setItem("UserFormData", JSON.stringify(form));

Then to retrieve this data you can use localStorage.getItem and parse it to object using JSON.parse.

JSON.parse(localStorage.getItem("UserFormData"));