简体   繁体   中英

javascript enter number of seconds - not less than zero

i am facing an issue in 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.

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.

 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.

Eg you could fill out your sec() function like this:

 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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