- Whitehorses - http://blog.whitehorses.nl -

Enforce the HTML5 max attribute of input items with JavaScript

Tweet [1]

The HTML5 max and min attribute on input items

The max attribute is introduced in HTML5 and specifies the maximum value for an <input> element. Unfortunately, it doesn’t enforce the maximum value entered when typing in numbers as you might expect.

The syntax for the HTML element is as follows:

<input max=”number|date“>

With a small JavaScript function it’s possible to make sure no value larger than the max value (or smaller than the min value) may be entered. Just put the following code in your $(document).ready(function) {}:

   $(document).on('keyup', '.myInputItem', function () {
      if (parseInt($(this).val()) >= $(this).attr('max'))

The function fires on the keyup event. The if statement compares the value of the input item with the max value. When it is higher, it will replace the contents with the max value.