Advertisements
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();
});
>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();
});