簡體   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