HTML5 input type=number change step behavior

mabs picture mabs · Jul 31, 2012 · Viewed 14.6k times · Source

If I use an input field of type="number" with step="100". I don't want odd numbers to be invalid. I just want increase or decrease to be with a value of 1000.

<input type="number" min="100" max="999999" step="100" />

If the user enters the value "199" and submits, he/she gets an error because the value isn't dividable by 100. But all I want with the step-value is to control the behavior of the spinner, e.g. if the user click up I want the value 199 to become 200 and if he/she clicks down I want it to become 100. Or ideally I would like the value to be increased or decreased with a value of 100.

How do I do this? I tried using the invalid event (with jQuery 1.7.2) like this:

$( "[type='number']" ).bind( 'invalid', function( e ) {
    var el = $( this ),
      val = el.val( ),
      min = el.attr( 'min' ),
      max = el.attr( 'max' );

    if ( val >= min && val <= max ) {
        return false;
    }
} );

But this results in the form not being submitted.

PS.: This is in Google Chrome 20.0.1132.57 on Fedora 16.

Answer

robertc picture robertc · Jul 31, 2012

I don't think you can, the step and the validation are closely tied together. In the future you may be able to override the stepUp() and stepDown() functions to get the behaviour you describe but I've not researched if this is an intended use case for these things. I would recommend posting on the WHATWG mailing list, asking specifically about those functions and describing your use case.

For current practical purposes have you tried setting step=1 and binding to a click event to capture? I can see there'll probably be an issue with distinguishing between 'up' and 'down' clicks but that might be surmountable. It might be easier all round however to use a text input, set the pattern attribute appropriately and implement your own spinner.