繁体   English   中英

javascript 输入秒数 - 不小于零

[英]javascript enter number of seconds - not less than zero

我在 javascript 中遇到问题。 我想做用户在输入字段中输入秒数。 但条件是users can't enter number of seconds less than zero.

如何使代码逻辑?

 function sec(){ //your code logic is here console.log("number of seconds is not less than"); }
 <form> <label for="seconds">Number of seconds:</label> <input type="number" id="seconds" name="seconds"> <button onclick="sec()">Click</button> </form>

我应该怎么办? 有人帮我吗?

将您对输入值的期望添加为输入的属性:

特别required min="0"将满足您的需求。

 function sec(){ //your code logic is here console.log("number of seconds is not less than"); }
 <form> <label for="seconds">Number of seconds:</label> <input type="number" id="seconds" name="seconds" required min="0"> <button onclick="sec()">Click</button> </form>

使用 JavaScript 您可以将用户的输入转换为数字,然后使用相等条件检查其值。

例如,您可以像这样填写您的 sec() function:

 function sec() { const seconds_str = document.getElementById("seconds").value; const seconds_num = parseInt(seconds_str, 10); // note: you could use parseFloat for decimal fractions let result = ""; if (seconds_num < 0) { result = "Is less than zero:'("; } else { result = "Is NOT less than zero:)"; } console.log("User input = " + seconds_str); console.log("Converted to integer = " + seconds_num); console.log(result); }
 <form> <label for="seconds">Number of seconds:</label> <input type="number" id="seconds" name="seconds"> <button onclick="sec()" type="button">Click</button> </form>

当您检测到小于零的数字时,您将做什么取决于您。 例如阻止表单提交、显示错误消息等...

暂无
暂无

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

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