I'm doing a small number keypad in Javascript, and I can't add a decimal point . to an <input type="number"> by doing:
document.getElementById('2').onclick = () => document.getElementById('input').value += '2';
document.getElementById('.').onclick = () => document.getElementById('input').value += '.';
<input id="input" type="number" value="3"></input>
<div id="2">click to add 2</div>
<div id=".">click to add .</div>
The specified value "3." cannot be parsed, or is out of range.
But on the other hand, we can manually enter the decimal point with the keyboard when the input has focus.
Full example:
var target = document.querySelector('#input');
document.querySelectorAll('.calcbutton').forEach(el => el.addEventListener("click", evt => { target.value += evt.target.innerHTML; }));
document.querySelector('.calcpoint').onclick = evt => { if (!target.value.includes('.')) target.value += '.'; };
<input id="input" type="number"></input>
<div id="calc">
<table>
<tr><td class="calcbutton">7</td><td class="calcbutton">8</td><td class="calcbutton">9</td></tr>
<tr><td class="calcbutton">4</td><td class="calcbutton">5</td><td class="calcbutton">6</td></tr>
<tr><td class="calcbutton">1</td><td class="calcbutton">2</td><td class="calcbutton">3</td></tr>
<tr><td class="calcbutton">0</td><td class="calcpoint">.</td><td class="calcenter">ENTER</td></tr>
</table>
</div>
Why does pressing . clear the input?
If a value is set (per JS), it works like the following (copy from specification)
That means it is immediately checked whether it fits the pattern of a number, whereas on a user input, it waits to a later point (basically to allow the ability to add decimal points)
See https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With