Announcement

Collapse
No announcement yet.

textbox that only accepts numbers greater than 0

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • textbox that only accepts numbers greater than 0

    Hello,

    I'm looking for a way to make my textbox only accept numbers. It needs to accept all numbers greater or equal to 0 and any number of decimals. No negatives.

    I found this online:

    <input type="number" min="0" oninput="validity.valid||(value='');">

    While this accomplishes almost everything I want, it has this odd glitch of not allowing any numbers in the decimal expansion except 0's. For example, if I type this:

    8.0000

    ...it accepts it, but if I try to type:

    8.00001

    ...it clears the field.

    Try it:

    https://jsfiddle.net/scrjhokk/

    If anyone can help me fix this one glitch, this would be perfect for me. If not, then can anyone suggest an alternative way of doing this?

  • #2
    Hi there gibby,

    you need to add the "step attribute" with a value that will match
    the maximum number of decimal places that may be required.

    Here is a basic example...

    Code:
    <form action="http://www.example.com">
     <input type="number" min="0" step="0.0000001" name="number" oninput="validity.valid||(value='')">
     <input type="submit">
    </form>
    Edit:

    A little more research revealed that...

    Code:
    
        step="any"
    
    ...is a more robust solution.

    Last edited by coothead; 07-06-2017, 04:51 AM. Reason: found an improvement for the code !!!


    ~ the original bald headed old fart ~

    Comment


    • #3
      Thanks coothead, that works.

      One thing I noticed with this is that I'm still able to add extra decimals. For example, I'm able to do this:

      0.6.

      It allows me to add that extra period after the 6. Anything I type after that gets wiped out, so it's still serving its purpose, but would you know if there's a way of preventing the user from entering that second period in the first place?

      Comment

      Working...
      X