javascript please input the number of seconds, ensuring it is a non-negative value

I'm encountering a JavaScript issue where I need users to enter a number of seconds in an input field. The catch is that

the number of seconds entered can't be less than zero.

How should I approach this logic in the code?

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

Can someone provide guidance on how to tackle this issue?

Answer №1

Set your expectations for the input value using attributes within your input element:

Specifically, including required min="0" will help fulfill your requirements.

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

Answer №2

By utilizing JavaScript, you have the ability to convert user input into a Number and then evaluate its value using an equality condition.

For example, you can modify your sec() function as follows:

function sec() {
  const seconds_str = document.getElementById("seconds").value;
  const seconds_num = parseInt(seconds_str, 10); // note: consider using 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>

Upon detecting a number less than zero, it is up to you how to proceed. You could choose to prevent form submission, display an error message, or take other actions...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

How to focus on a dynamically changing input box in Vue

In my form, users can input an email address and click a plus button to add another input box for a new email address. These input boxes are created by iterating over an array, so when the user clicks on the plus icon, a new entry is added to the array. W ...

Tips on persisting dynamic form data using JavaScript and a database query

I have a unique script that generates dynamic form content with inputs named "field-1", "field-2", and so on until the last input is created. How can I effectively save this dynamically generated form to the database? Usually, I would create a form with ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

Syntax error is not caught - why are there invalid regular expression flags being used?

I'm attempting to dynamically create rows that, when clicked, load a view for the associated row. Check out my javascript and jquery code below: var newRow = $('<tr />'); var url = '@Url.Action("Get", "myController", new ...

Elevation in design ui component

I am having an issue with the height of a theme-ui component I embedded. Even though the console shows it correctly, it is displaying at 100% height. <Embed src={url} sx={{width: '800px', height: '400px'}}/> This embed is contain ...

How should the nonce be properly set in the csp policy?

I've been attempting to incorporate a nonce into the csp policy but it's not functioning as anticipated. Here's the code snippet I'm currently using for testing purposes: server.js express.use(function(req, res, next) { res.set( ...

Error 107 occurred while attempting to parse JSON data using the AJAX technique with the REST API

I've encountered an issue while attempting to utilize the Parse REST API for sending push notifications. Every time I make an AJAX call, I receive an invalid JSON error in the response and a status code of 400. Below is my request: $.ajax({ url: & ...

Is it possible to create a React Component without using a Function or Class

At times, I've come across and written React code that looks like this: const text = ( <p> Some text </p> ); While this method does work, are there any potential issues with it? I understand that I can't use props in this s ...

How can we retrieve the value from a textBox using JavaScript in Selenium WebDriver?

https://i.sstatic.net/6ni0f.pngTrying to extract text from an input tag that is missing in the HTML code, leading to the need for JavaScript to retrieve the value. Unfortunately, running the code in Eclipse returns null as the result. The HTML and Seleni ...

Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID ...

What causes a function loss when using the spread operator on window.localStorage?

I am attempting to enhance the window.localStorage object by adding custom methods and returning an object in the form of EnhancedStorageType, which includes extra members. Prior to using the spread operator, the storage.clear method is clearly defined... ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...

How to resolve the error of "Objects are not valid as a React child" in NextJs when encountering an object with keys {children}

I am currently working on a nextjs application and I have encountered an issue with the getStaticPaths function. Within the pages folder, there is a file named [slug].tsx which contains the following code: import { Image } from "react-datocms"; i ...

What are the top methods for interacting between Server APIs and Client-Side JavaScript?

Presently, I am utilizing setTimeout() to pause a for loop on a vast list in order to apply some styling to the page. For example, For example: How I utilize setTimeOut: I use setTimeout() to add images, text and css progress bars (Why doesn't Prog ...

Merge the content of a single file with the contents of several other files using Gulp

I'm still getting the hang of Gulp, so I hope this question isn't too basic. My project is pretty complex with multiple files, and thanks to Gulp's magic, I can combine, minify, babel, and more. I've been using Grunt for a long time, so ...

When incorporating script tags in React, an "Unexpected token" error may arise

I am in the process of converting my website to a React site, but I am encountering an issue with the script tags not working. It keeps showing an unexpected token error. Here is the code snippet: <div className="people"> How many people are you ...

ASP.NET Dynamic Slideshow with Horizontal Reel Scrolling for Stunning

I'm curious if there is anyone who can guide me on creating a fascinating horizontal reel scroll slideshow using asp.net, similar to the one showcased in this mesmerizing link! Check out this Live Demo for a captivating horizontal slide show designed ...

The nonexistence of the ID is paradoxical, even though it is present

I've been working on a school project that involves a dropdown box with the id "idSelect." However, I'm encountering an issue where it says that idSelect is not defined when I try to assign the value of the dropdown box to a variable. Even after ...