JavaScript输入字段onChage/oncut
请帮助,如何在JavaScript中进行这样的输入? 可以输入的最小数字= 0.01 可以输入的最大数字= 94.99 如果它通过最小/最大值,它将自动返回最小/最大值的默认号码。 同时,如果输入数字01.21,该数字将自动更改为1.21,
感谢您花时间回答并提供方向。
想创建类似于此的输入字段>
function minmax(value, min, max) {
if (parseInt(value) < 0.01 || isNaN(value))
return 0.01;
else if (parseInt(value) > 94.99)
return 94.99;
else return value;
}
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0.01, 94.99)" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您甚至不需要为此使用JavaScript,只是Plain HTML可以解决您的问题。
input
标签具有代码>最大属性设置输入的最小值和最大值。另外,您可以设置step
step 0.01。这应该在前端解决您的问题。但是请注意,这还不足以确保后端收到的数据(如果是这样)遵循您的规格,因为恶意用户可以更改页面并反正发送数据,甚至绕过前端完全地。因此,后端还应检查收到的数据是否以正确的格式。
You probably don't even need to use JavaScript for this, just plain HTML can solve your problem. The
input
tag has themin
andmax
properties that set minimum and maximum values for the input. Also, you could set thestep
of your input to 0.01.This should solve your problems on the front-end. But note that this isn't enough to ensure that the data received by the back-end (if that's the case) is following your specifications, because malicious users can alter your page and send the data anyways, or even bypass the front-end completely. So, the back-end should also check if the data received is on the right format.
您可以使用 onChange 事件或添加 event listerner 到输入字段和最小值,最大值以指定最大和最小数字。
然后,您可以使用JavaScript使用IF条件将用户输入的值与最小值和最大值比较。如果用户输入的值无效,只需用最小值或最大值替换输入字段值即可!
使用 parsefloat()因为您正在与floats打交道。
最后一部分 parsefloat 。
You can use onchange event for this or add an event listerner to the input field and min, max to specify the maximum and minimum number.
Then you can use javascript to compare the user entered value with min and max values using an if condition. If the user entered value is invalid simply replace the input field value with either min or max value!
Use parseFloat() since you are dealing with floats.
And for the last part the parseFloat will automatically do that for you by clearing the leading zeroes.
onChange
方法else返回值-0.01;
返回float值parseInt()
返回整数value使用parsefloat()
返回float阀值-0
删除无用的值,如01.11
to 1.11`onchange
methodelse return value - 0.01;
return float valueparseInt()
return integer value useparseFloat()
return float valvevalue - 0
remove useless 0 in value like01.11
to 1.11`有两个事件处理程序
limitrange()
绑定到输入事件,keepdot()
绑定到键盘事件(设置在捕获上,请注意,第三个参数为true
)。keepdot()
只需处理Firefox拒绝接受。键的方式即可。它有两个工作。第一份工作是限制低于.01或高于94.99的输入,
第二个工作是删除任何领先的零
There are two event handlers
limitRange()
is bound to the input event andkeepDot()
is bound to the keyup event (set on capture, note the third parameter istrue
).keepDot()
just handles the way Firefox refuses to accept the . key.It has two jobs. First job is to limit input lower than .01 or higher than 94.99
The second job is to remove any leading zeros
在这里,您需要使用 parsefloat() 因为您使用浮动值。
Here you need to use parseFloat() since you are using floating values.