How to automatically increment text value on sequential inputs
I have this unordered list which contains some inputs, what I want to do is to type a value on the first i开发者_JAVA技巧nput, like "1", then all the other inputs, in order, gets 2, 3, 4, 5
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.
You could use the each function of jQuery. Something similar to the following:
var counter=Number($("input[selector for your first textbox]").val());
$("input[selector for inputs in your list]").each(function()
{
this.val(++counter);
}
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.
精彩评论