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

How to prevent localStorage from saving same data

I made a program where anyone can log-in, but the problem is that it saves same names even if it’s already their in localStorage. I want it not to get saved when it’s already having the same name in localStorage

Here is my HTML5 & js code

<!-- HTML5 -->
<div>
  <!-- login -->
  <form>
    <!-- UserName -->
    <input id="name" type="text" placeholder="Enter name">
    <br>
    <!-- password -->
    <input id="password" type="password" placeholder="Enter password">
    <br><br>
    <!-- login button -->
    <button id="saveButton">Log in</button>
    <br><br>
  </form>
  <script src="./saveName.js"></script>
  <script src="./savePassword.js"></script>
</div>
//JAVASCRIPT
function saveNames() {
  var newNames = document.getElementById('name').value;

  if (localStorage.getItem('id') == null) {
    localStorage.setItem('id', '[]');
  }

  var old_data = JSON.parse(localStorage.getItem('id'));

  old_data.push(newNames);

  localStorage.setItem('id', JSON.stringify(old_data));

  alert(localStorage.getItem('id'));
}

saveButton.addEventListener("click", function(e) {
  e.preventDefault();
  saveNames();
});

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 :

function saveNames() {
  var newNames = document.getElementById('name').value;

  if (localStorage.getItem('id') == null) {
    localStorage.setItem('id', '[]');
  }

  var old_data = JSON.parse(localStorage.getItem('id'));
  if (!old_data.includes(newNames)) {
  old_data.push(newNames);

  localStorage.setItem('id', JSON.stringify(old_data));
alert(localStorage.getItem('id'));
}
else return
}

saveButton.addEventListener("click", function(e) {
  e.preventDefault();
  saveNames();
});
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