[英]How to make starting value in input and replacing this value while keyboard input?
h1 { font-size: 20px; } input { height: 45px; width: 300px; font-size: 30px; direction: rtl; }
<h1>starting value 0.00</h1> <h1>if type 1 from keyboard update value as 0.01</h1> <h1>if type next 1 from keyboard update value as 0.11</h1> <h1>if type next 1 from keyboard update value as 1.11</h1> <input type="text">
in html in the markup of your input element, have this: oninput="this.value = this.value.toFixed(2)"
在输入元素的标记中的html中,有这样的: oninput="this.value = this.value.toFixed(2)"
So this would look like in your markup: 所以这看起来像你的标记:
<input
oninput="this.value = this.value.toFixed(2)"
/>
Now toFixed() transforms the thing into a string as well so it might not be what you're trying to do, it seems that adding those two decimal places and how to do it best to be compatible across all browsers and consisten is still up for debate, these stackoverflow threads are full of options: Round to at most 2 decimal places (only if necessary) JavaScript math, round to two decimal places [duplicate] 现在toFixed()将事物转换为字符串,所以它可能不是你想要做的事情,似乎添加这两个小数位以及如何最好地兼容所有浏览器并保持一致仍然是为了辩论,这些stackoverflow线程充满了选项: 舍入到 最多2个小数位(仅在必要时) JavaScript数学,舍入到两个小数位[重复]
document.querySelector('input').addEventListener('keypress', function(e) { e.preventDefault(); const oldVal = this.value, newVal = oldVal.replace(/(0)(?!.*\\1)/, e.key); this.value = newVal === oldVal ? `${e.key}${oldVal}` : newVal; });
h1 { font-size: 20px; } input { height: 45px; width: 300px; font-size: 30px; direction: rtl; }
<h1>starting value 0.00</h1> <h1>if type 1 from keyboard update value as 0.01</h1> <h1>if type next 1 from keyboard update value as 0.11</h1> <h1>if type next 1 from keyboard update value as 1.11</h1> <input type="text" value="0.00">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.