MHasan
MHasan

Reputation: 69

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?

Upvotes: 0

Views: 835

Answers (2)

Karl Bishop
Karl Bishop

Reputation: 391

With JavaScript you can convert your user's input to a Number then check its value with an equality condition.

E.g. 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. E.g. prevent form submitting, show an error message etc...

Upvotes: 0

Chase
Chase

Reputation: 3126

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>

Upvotes: 1

Related Questions