简体   繁体   English

javascript 输入秒数 - 不小于零

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

i am facing an issue in javascript.我在 javascript 中遇到问题。 i want to do user enter number of seconds in input field.我想做用户在输入字段中输入秒数。 but the condition is that users can't enter number of seconds less than zero.但条件是users can't enter number of seconds less than zero.

how can a make the code logic?如何使代码逻辑?

 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>

what should i do?我应该怎么办? anyone help me?有人帮我吗?

Add your expectation about the input value as attributes on your input:将您对输入值的期望添加为输入的属性:

Specifically required min="0" would meet your needs.特别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>

With JavaScript you can convert your user's input to a Number then check its value with an equality condition.使用 JavaScript 您可以将用户的输入转换为数字,然后使用相等条件检查其值。

Eg you could fill out your sec() function like this:例如,您可以像这样填写您的 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>

It would be up to you what you do when you detect a number less than zero.当您检测到小于零的数字时,您将做什么取决于您。 Eg prevent form submitting, show an error message etc...例如阻止表单提交、显示错误消息等...

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

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