Today I have a tricky (for me at least) question. There is a bug in my code, I don't know how to eliminate it. Basically I'm creating a simple Form in JavaScript as an homework, and I encountered this problem.
I have to enter my age in this form, and for now it's all ok. But I have to enter it twice: one with an <input> tag and one with a popup window. I can input the value in the <input> tag just fine, but when I'm trying to input the value by the prompt(), it "resets" the script, so I lose the value in the <input> object.
I need a way to store these information somewhere, or stop the prompt() from deleting these values or resetting the page.
<html lang="en">
<head>
<title>Document</title>
<style>
* {margin: 0; padding: 0;}
body {padding: 20px;}
</style>
<script>
var eta_btn;
function eta_controllo(eta_btn) {
eta_btn = Number(prompt("Inserisci la tua età"));
console.log(eta_btn);
}
function profession() {
var temp = document.getElementById("select").selectedIndex;
if (temp == 0) {
document.getElementById("lavoratore_txt").style.display = "";
document.getElementById("studente_txt").style.display = "none";
} else if (temp == 1) {
document.getElementById("studente_txt").style.display = "";
document.getElementById("lavoratore_txt").style.display = "none";
} else {
document.getElementById("studente_txt").style.display = "none";
document.getElementById("lavoratore_txt").style.display = "none";
}
}
function send_to_server() {
if (!(eta_btn == document.getElementById("età").value)) {
alert("Le due età inserite non sono concordi");
return false;
}
else if (eta_btn == document.getElementById("età").value && eta_btn < 14) {
alert("Hai meno di 14 anni!");
return false;
} else if (confirm("Sicuro di aver scelto la provincia " + document.querySelector('input[name="città"]:checked').value))
alert("Dati inviati correttamente");
else {
alert("Errore");
return false;
}
}
</script>
</head>
<body>
<form action="">
<p>NOME</p>
<input placeholder="scrivi qui il tuo nome" type="text"><br><br>
<p>PASSWORD</p>
<input placeholder="scrivi qui la tua password" type="text"><br><br>
<p>ETA'</p>
<input placeholder="scrivi qui la tua età" type="text" id="età">
<button onclick="eta_controllo()">CONTROLLO</button><br><br>
<input name="città" type="radio">GENOVA<br>
<input name="città" type="radio">SAVONA<br>
<input name="città" type="radio">IMPERIA<br>
<input name="città" type="radio">LA SPEZIA<br><br>
<select name="" id="select" onchange="profession()">
<option value="lavoratore">Lavoratore</option>
<option value="studente">Studente</option>
<option value="disoccupato">Disoccupato</option>
</select>
<p id="studente_txt" style="display: none">Vai a studiare!</p><br>
<textarea id="lavoratore_txt" style="display: none;" name="" id="" cols="30" rows="10"></textarea><br><br>
<button>ANNULLA TUTTO</button>
<button onclick="send_to_server()">INVIA AL SERVER</button>
</form>
</body>
</html>
eta_btninto theeta_controllo()function?