Eu tenho essas três entradas do tipo número onde você só pode adicionar um número e pode substituí-lo pressionando qualquer outro número entre 0 e 9. Eu tenho 2 eventlisteners nessas entradas o primeiro é poder alterar o valor das entradas pressionando um número entre 0 e 9 (usando 'keyup').
O segundo eventlistener existe para detectar a entrada e então calcular o total das três entradas, quando o total correto é calculado, um alerta é lançado. O que percebi é que se eu quiser um total de 27 por exemplo preciso somar 9 + 9 + 9 nas entradas.
Porém, se eu adicionar 9 + 8 + 9, mas sem excluir o 8 e apenas substituí-lo pressionando 9, não recebo o alerta. Para obter o total, melhor parece fazê-lo no ouvinte de eventos com 'keyup'.
Então por que isso? Ao pressionar o botão 9 ainda é um evento de entrada?
const element1 = document.querySelector('.element1')
let total = 0
let desiredTotal = 27
let allInputs = Array.from(element1.getElementsByTagName('input'))
allInputs.forEach((input)=>{
input.style.border = '2px solid blue'
input.addEventListener('keyup', (e)=>{
if(e.target.value.length === 1 && parseFloat(e.key) >= 0 && parseFloat(e.key) <=9){
e.target.value = e.key
}
})
})
allInputs.forEach((input)=>{
let value
input.addEventListener('input', (e)=>{
let value = parseFloat(input.value)
total += value
console.log(total)
if(total === 27) alert('you won!')
})
})
input{
width: 2ch;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
appearance: textfield;
}
<body>
<div class="element1">
<input type="number" name="" id="input1" onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
<input type="number" name="" id="input2" onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
<input type="number" name="" id="input3"onKeyPress="if(this.value.length===1 || event.key == 'e') {return false}">
</div>
<p>Try to obtain a total of 27</p>
<p>Try to place 9 9 and then 9 you get the alert</p>
<p>Try to place 9 6 and then 9 but then change(without deleting) but pressing on the 6 containing input the number 9 you won't get the alert</p>
</body>
Não misture entrada HTML onKeyPress e JS EventListener.
Faça tudo em JS