When a user is typing just ‘e’ in a input element of type number the value of the element in JavaScript is empty, same if a user empties the input element.
I have tried different events (input, keyup, blur), but all return “” if the one types ‘e’. I don’t want to block it, just to know if the input element is visually empty.
Is there a way to check if the user has typed ‘e’ in a input number element?
const testElement = document.getElementById("number-input"); const direct = document.getElementById("direct"); let lastV; const setOut = (v, id) => { const out = document.getElementById(id); out.innerHTML = v; }; testElement.addEventListener('input', e => setOut(e.target.value, 'input-ex')); testElement.addEventListener('keyup', e => setOut(e.target.value, 'keyup-ex')); testElement.addEventListener('blur', e => setOut(e.target.value, 'blur-ex')); document.getElementById("directBtn").addEventListener('click', e => setOut(testElement.value, 'direct-ex')); document.getElementById("clrBtn").addEventListener('click', () => { testElement.value = null; })
<input id="number-input" type="number"> <button id="directBtn"> get direct </button> <button id="clrBtn"> clear </button> <p id="out"> Input <span id="input-ex"></span> <br/> Key up <span id="keyup-ex"></span> <br/> Blur <span id="blur-ex"></span> <br/> Direct <span id="direct-ex"></span> <br/> </p> <p id="direct"> </p>
Advertisement
Answer
I would can use keydown
since that event fires before the input’s value property changes… Since, for example “12e” is not a valid number, that’s is why property changes to “” (empty). But “12e3” is valid.
But checking the event key
also will work on keyup
and keypress
.
const testElement = document.getElementById("number-input"); const direct = document.getElementById("direct"); let lastV; const setOut = (v, id) => { const out = document.getElementById(id); out.innerHTML = v; }; testElement.addEventListener('input', e => setOut(e.target.value, 'input-ex')); testElement.addEventListener('keyup', e => setOut(e.target.value, 'keyup-ex')); testElement.addEventListener('blur', e => setOut(e.target.value, 'blur-ex')); document.getElementById("directBtn").addEventListener('click', e => setOut(testElement.value, 'direct-ex')); testElement.addEventListener('keydown', e => { if(e.key==="e"){ setOut(e.key, 'keydown-ex') } }); document.getElementById("clrBtn").addEventListener('click', () => { testElement.value = null; })
<input id="number-input" type="number"> <button id="directBtn"> get direct </button> <button id="clrBtn"> clear </button> <p id="out"> Input <span id="input-ex"></span> <br/> Key up <span id="keyup-ex"></span> <br/> Blur <span id="blur-ex"></span> <br/> Direct <span id="direct-ex"></span> <br/> <br/>Key Down <span id="keydown-ex"></span> <br/> </p> <p id="direct"> </p>