Thookes
Thookes

Reputation: 99

Is there any way to control a number input's increment event, or make two number inputs work together?

I'm developing a website where I used number inputs to get a reservation's duration, by asking the user to specify the start and end time of it. I'd like to limit the input fields in a way that doesn't let the user choose an earlier end time than start time, and vice versa. I managed to do this with JavaScript, but in this way you need to increment the end time value in order to be able to increment the start time's value, and I don't think this is a good practice. For example, if the first field's value is 8, and it's limited to be lesser, than the second's value, which is 9, I'm not able to increment the first number input's value as long as I don't increment the second one's.

So, I would like to control the first input field's increment event (or whatever it's called) so I can also increment the second input field's value, when the first's value is exactly equal with [second's value - 1]. I know there's not much support for this type of input field yet, but however, is there any way to do this?

max = parseInt(endtime.value, 10) - 1;
min = parseInt(starttime.value, 10) + 1;
starttime.setAttribute('max', max);
endtime.setAttribute('min', min);

This is the JavaScript code to limit the two number input fields. But unfortunately I couldn't write any code that increments the second field's value when I increment the first one, or lowers the first's value when I lower the second one. I couldn't find any examples or information about what event fires when I press the up/down arrows of number input fields.

Upvotes: 3

Views: 586

Answers (1)

Artur Filipiak
Artur Filipiak

Reputation: 9157

A bit messy :-) and most likely can be improved, but do the job (If I well understand the question). Added basic validation, but can be replaced with anything.

HTML:

<input id="start" min="0" max="23" class="txt" type="number" value="0"/>
<input id="end" min="0" max="23" class="txt" type="number" value="1"/>

jQuery:

$('.txt').keyup(function(){
    checkit($(this));
}).change(function(){
    checkit($(this));
});

function checkit(el){
    var txt = el.val(),
        el2 = $('.txt').not(el),
        txt2 = el2.val(),
        id   = el.attr('id');
    if(!$.isNumeric(txt)){
        el.val(0);
        return checkit(el);
    }
    var t  = parseInt(txt),
        t2 = parseInt(txt2);
    if(t > 23 || t < 0) {
        el.val(0);
        return checkit(el); 
    }
    var c  = (id == 'end') ? 
             (t <= t2 ? (t <= 0 ? 0 : 
             (t <= 0 ? 1 : t-1)) : t2) : 
             (t >= t2 ? (t >= 23 ? 23 : 
             (t >= 23 ? 22 : t+1)) : t2),
         s = ((c == 0 && id == 'end' && t == 0) ? 1 : 
             ((c == 23 && id == 'start' && t == 23) ? 22 : t));

    el.val(s);
    el2.val(c);
}

JSFiddle

JSFiddle (extended, w/bootstrap)

Upvotes: 1

Related Questions