befb
befb

Reputation: 21

<Input type ="number"> should only accept positive integers

This HTML code still allows me to write .

So if a user writes 1.2 that will automatically be converted to 12.

I don't want to allow the user to write . itself.

Also, though it doesn't allow the user to start with the - sign it allows the user to enter it in the middle like 21- but then it immediately resets the entire field to blank.

How do I fix this so that it only accepts positive integers?

<input type="number" min="30" max="300" step="1" oninput="validity.valid||(value=value.replace(/\D+/g, ''))" style="width:4em" id="seconds" name="seconds" value="30" onmouseout="setBounds()" />

setBounds() has the functionality so the user can only enter between 30 and 300

Upvotes: 1

Views: 1902

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65873

You can set up a keypress event handler for the element that checks the key that is being pressed and cancels the event upon the . or - entries with event.preventDefault(), like this:

const input = document.getElementById("seconds");

// Set your event handlers up in JavaScript, not with
// inline HTML event attributes
input.addEventListener("keypress", function(event){
 if(event.key === "." || event.key === "-"){
   event.preventDefault(); // Cancel the native operation
 }
});
<input type= "number" min="30" max="300" step="1" id="seconds" name="seconds" value="30">

But, because you have a specific range in mind, you may want to consider using an input type="range" which eliminates the potential for the problem in the first place:

// Get reference to the input and the output elements
const input = document.getElementById("seconds");
const output = document.getElementById("output");

output.textContent = input.value;  // Initialize the output

// Set your event handlers up in JavaScript, not with
// inline HTML event attributes
input.addEventListener("input", function(event){
  output.textContent = this.value; // Update the output
});
<input type= "range" min="30" max="300" step="1" id="seconds" name="seconds" value="30">
<span id="output"></span>

Upvotes: 2

Related Questions