HTML input number step without validation
Asked Answered
V

2

11

In HTML you can add the step attribute to inputs of type number. I wanted this because I liked how it can simplify the input for the user, by only pressing the up/down key.

I found out that an additional feature of this attribute is, that it forces the user to stay in that interval. HTML does this with validation. You can enter any value manually, but it won't let you submit the form. I don't want this!

To work around with this, I found that there is a novalidate attribute that is used in the <form> tag, which works great. But sadly, the browser support is poor.

I guess I'd need to remove the step attribute and write the functionality by myself with JavaScript/jQuery by triggering the keydown event on it.

Violence answered 7/1, 2017 at 15:19 Comment(1)
I think I have the same question / problem. This did not work for me: <input type="number" name="futureDailyAdSpend" value="138.03" step="50" min="50" formnovalidate/>. I get this error: "Please enter a valid value. The two nearest valid values are 100 and 150." I want to allow users to click the up/down arrows to step in increments of 50, but I also want to allow users to type in a more precise number.Photima
R
2

But sadly, the browser support is poor.

That's not true. According to MDN, IE supports the novalidate attribute since version 10, and input[type=number] also since version 10. This means that if a browser supports number inputs, it most likely also supports the novalidate attribute.

Ruzich answered 7/1, 2017 at 15:28 Comment(1)
According to w3schools it does offer no support for safari, but I just tested it and it seems that there is no validation at all for steps in safari, so it's ok. I will just go with it :) thank youViolence
M
1

This is a React implementation but there is a way to achieve this. Essentially:

  • Set step as "any" (effectively disables the browser restriction on the value, no validation applies, BUT the stepper still appears)
  • Control the input value from JS
  • Track stepper/arrow changes by using inputType to differentiate between typing/pasting input vs stepper/arrow input
  • Detect stepper/arrow events via mouse events, manually apply the change to the input value

See the working example here.

Magnetometer answered 22/3 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.