Dude, try it this way. I don’t know your real need, but this way you can have a basis.
If the entered value is already inside the array, an alert message will appear and the number will not be entered. The field is also cleared after you click the "Validate your Answer".
The index looks if that value that is in it as parameter is present in that specified array (in the code of that code, the Array "Usu"). When it does not contain the value, it is returned -1.
Push adds that element that is in it as a parameter, in the first empty position of the Array. (In the case of this code here, add the value of the variable "bot" in the array "Usu").
See in the.log console that the values entered in the Array are displayed there.
<html>
<body>
<h3>Entre com sua aposta para mega sena (Com 6 números)</h3>
<input type="text" id="campo-texto">
<br>
<input type="button" id="botao" value="Valide sua aposta" onclick="gerar()">
<div id="correto">
<h1>Números Corretos</h1>
</div>
<div id="incorreto">
<h2>Números Incorretos</h2>
</div>
<script>
var usu = new Array();
function gerar() {
var bot = document.getElementById("campo-texto").value;
if (usu.indexOf(bot) == -1) {
if (bot != "") {
usu.push(bot);
console.log(usu);
document.getElementById("campo-texto").value = "";
} else {
alert("O campo está vazio");
}
} else {
alert("O número já existe no Array");
}
}
</script>
</body>
</html>
Man, I’m sorry but your code is very wrong and badly explained. Put your full code in so we can understand better.
– Gato de Schrödinger
I’ll be editing the code
– Kayo Rodrigo
Man, this html has some heim errors. But tell there what values of this code you want to put in an array?
– Douglas Benitez
I asked another question explaining my problem better, I appreciate the attention. I’ll be passing the link here: link
– Kayo Rodrigo