Dimitar
Dimitar

Reputation: 1928

input "step" dosent work with jQuery & HTML5. why?

I am using HTML5 & jQuery to use the "step" attr in the input tag in HTML. It is working great, but what I want to do is start the default value as 1 and then the step must be 33 (which is again calculating using javascript and it is changing every time, but in this case it should be 33) and i want the numbers to be 33 and NOT 34 (because the default value is 1 + the step of 33 = 34), but i want to be 33, 66, 99... and so on. I'm using this code to do this:

HTML:

<input type="number" min="1" name="numeration_from" value="1">

jQuery:

$("input[name='numeration_from']").change(function () {
    $(this).val(Number($(this).val() - 1));
});

$("input[name='numeration_from']").attr("step", 33);

but you can see from here: http://jsfiddle.net/bulgaria_mitko/S8fC9/ that it is doing something wrong. it is going from 1 to 33 and then when i press the up key it is going to 34 and then to 66 and then to 67 and then to 99 and then 100 and so on. Why?

It's supposed to go to 33 then 66 then 99! I need help!

Upvotes: 0

Views: 1786

Answers (2)

vvohra87
vvohra87

Reputation: 5664

The problem is that the HTML step computation takes the min into account when changing the number. Also, when you hook into an input's change method, it's good practice to return false to prevent cyclic loops when you're changing the value of the same input.

Working fiddle: http://jsfiddle.net/bulgaria_mitko/S8fC9/

HTML:

<input type="number" min="0" name="numeration_from" step="33">

JS:

$("input[name='numeration_from']").val(1);
$("input[name='numeration_from']").change(function () {
    if($(this).val() == 1){
        $(this).val(Number($(this).val() - 1));
        return false;
    }
    if($(this).val() == 0){
        $(this).val(Number($(this).val() + 1));
        return false;
    }
});

Upvotes: 1

Ronald Toussaint
Ronald Toussaint

Reputation: 21

When you have set min=1 and step=33, your input accepts the following values: 1, 34, 67, 100,... You then substract 1 when the change-event is fired. The next value it accepts, is then the value before the substraction. So when it's 34, you substract 1, so it becomes 33. The next value it accepts is again 34 then.

Upvotes: 0

Related Questions