简体   繁体   English

如何在输入中创建起始值并在键盘输入时替换此值?

[英]How to make starting value in input and replacing this value while keyboard input?

  1. How to make starting value 0.00 in input? 如何在输入中使起始值为0.00?
  2. And how to replacing this value while keyboard input? 以及如何在键盘输入时替换此值? (if type 1 from keyboard: 0.01, 0.11, 1.11) (如果键盘输入1:0.01,0.11,1.11)

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM