I have this unordered list which contains some inputs, what I want to do is to type a value on the first input, like "1", then all the other inputs, in order, gets 2, 3, 4, 5
3 Answers
You could do something like this, parse the first value then increment the rest based on their index:
$("ol input:first").keyup(function() {
var val = parseInt(this.value, 10);
$("ol input:gt(0)").val(isNaN(val) ? '' : function(i) { return val + i + 1; });
});
You can give it a try here. The if/else conditional is checking if the value's legit, e.g. if you hit backspace and it's empty you won't get NaN in every following input, inside we'll blank out the value so it's handled gracefully.
1 Comment
Vitor Reis
Love your solution, Nick. still I need to type a value on any given input and all the others ahead gets the value increment.. Like, I type 1 on the 1st, then all the others get 2,3,4,5. But if I go and change 4 to 10, the 5 go to 11, and the others remain untouched
Given the following markup, you can use jQuery to set the values:
<ul>
<li><input id="start" type="text" /></li>
<li><input class="auto" type="text" /></li>
<li><input class="auto" type="text" /></li>
<li><input class="auto" type="text" /></li>
<li><input class="auto" type="text" /></li>
</ul>
And the jQuery:
$(document).ready(function() {
$("#start").change(function() {
// Get the value entered
var value = new Number($(this).val());
// Increment the other fields
$(".auto").each(function() {
value++;
$(this).val(value);
});
});
});
See the working example here. Note, there's no validation on this, but it'll give you another idea of how to accomplish what you're after.