I'm doing a bit of a registration with the localStorage, and using a counter to put the name, differentiating one I give another. And then in a loop to show the result in a table with innerHTML, there is the problem, it appears and at the same time some.
HTML code:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8"/>
<title>HTML5 - Estrutura Básica</title>
<link rel="stylesheet" href="css/cadastro.css" />
<script src="js/script.js"></script>
</head>
<body>
<form>
<fieldset id="usuario">
<legend>Cadastro</legend>
<p><label for="cCodigo">Código:</label> <input type="text" id="cod" name="Codigo" size="10" maxlength="10" placeholder=" Código"/> </p>
<p><label for="cNome">Nome:</label> <input type="text" id="name" name="Nome" size="35" maxlength="35" placeholder=" Nome Completo" /></p>
<p><label for="cIdade">Idade:</label> <input type="text" id="age" name="Idade" size="5" maxlength="5" placeholder=" Idade" /></p>
<input type="submit" value="Salvar" onClick="salvar()" />
<input type="submit" value="Mostrar" onClick="mostrar()" />
<input type="submit" value="Total" onClick="total()" />
<input type="submit" value="Limpar" onClick="limpar()" />
</fieldset>
</form>
<table border="1" id="tabela">
<tr>
<th>Nome</th>
<th>Idade</th>
</tr>
</table>
</body>
JavaScript code:
function salvar(){
var cod = document.getElementById("cod").value;
localStorage.setItem("nome" + cod, document.getElementById("name").value);
localStorage.setItem("idade" + cod, document.getElementById("age").value);
alert("Dados Atualizados");
}
function mostrar(){
var i = 1
while (i < (localStorage.length/2)+1){
document.getElementById("tabela").innerHTML += "<tr>" + "<td>" + "NOME : " + localStorage.getItem("nome" + i)+ "</td>" + "<td>" + "IDADE :" + localStorage.getItem("idade" + i) + "</td>" + "</tr>"
i++;
}
}
function total(){
alert(localStorage.length/2);
}
function limpar(){
i = 0;
cod = 0;
localStorage.clear();
alert("Dados apagados!")
}
If anyone can help, thank you: DD