简体   繁体   English

使用 Javascript 输入小于或等于值

[英]Enter less than or equal value using Javascript

I am trying to given alert to the user, if user enter more than input variable value.如果用户输入的变量值超过输入变量值,我正在尝试向用户发出警报。

problem statement: Max_ava_water = 300问题陈述: Max_ava_water = 300

if user enter a 6 also it is showing 'Enter less or Equal values'.如果用户输入 6,它也会显示“输入更少或相等的值”。

 var Max_ava_water = 300 $('#input_rd').keyup(function() { if ($(this).val() > Max_ava_water) { console.log("Enter less or Equal values") $(this).val(''); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="value" id="input_rd" />

You're checking on every keyup event, which is too soon — the user could be trying to type 600, which starts with 6, which is less than 100. (Sorry, that comment was when I'd misread your > as < . But the basic idea still applies.)您正在检查每个keyup事件,这为时过早 — 用户可能试图键入 600,它以 6 开头,小于 100。(抱歉,该评论是我将您的>误读为< 。但基本思想仍然适用。)

Instead, check when the field loses focus ( blur ) or when they try to confirm the value in some other way.相反,检查字段何时失去焦点 ( blur ) 或他们何时尝试以其他方式确认值。

I'd strongly suggest not clearing the field when the value is too low.当值太低时,我强烈建议不要清除该字段。 Instead, let them edit the value (maybe they just missed out a 0 at the end).相反,让他们编辑值(也许他们只是在最后遗漏了一个0 )。

 const Max_ava_water = 300; // Using `blur` event $('#input_rd').on("blur", function() { // Explicit conversion const value = this.value ? parseInt(this.value, 10) : NaN; // Note that `NaN` is never `>` anything if (value > Max_ava_water) { console.log("Enter less or Equal values") } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="number" id="input_rd" />

Also note that type="value" is invalid forinput fields .另请注意type="value"input字段无效。 You could use type="number" as I did above to trigger the browser's standard handling for number fields, perhaps with min and max to do range checking.您可以像我上面那样使用type="number"来触发浏览器对数字字段的标准处理,也许使用minmax进行范围检查。


Side note: val returns a string (or undefined if you call it on an empty jQuery set, but you aren't).旁注: val返回一个字符串(或者undefined如果你在一个空的 jQuery 集上调用它,但你不是)。 Your expression relies on > to implicitly convert that to a number.您的表达式依赖于>将其隐式转换为数字。 > does do that, but often it's better to do the conversion intentionally, not least because the rules for implicit conversion might not be the rules you want to apply ( "" converts to 0 , for instance). >确实这样做了,但通常最好是有意地进行转换,尤其是因为隐式转换的规则可能不是您想要应用的规则(例如, ""转换为0 )。 My answer here describes your various options and their pros and cons.在这里的回答描述了您的各种选择及其优缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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