How do I start jQuery $.each()
index from 1 instead of 0?
I am using .each function to populate select box. So here I want to populate options in the se
This is what I did:
var start = index + 1;
This just adds 1 to the current index.. then use that new variable instead of 'index'.
var data = [42, 1337];
$.each(data, function(i) {
i++;
console.log(i);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.each
So try
$.each(obj, function(i, elem) {
if (i === 0) return;
// do stuff
});
Alternatively rewrite your code so its so indexes and data start at 0. JavaScript is interally 0 based rather then 1 based like Matlab and some other languages.
Seeing the clarification points in the comments below, jQuery.each
or some variation thereof isn't the right tool at all. Use a for loop, and add 1 to the index to output the value of the <option>
.
Use .prepend
to insert an option
as the first child of a select
:
for (var i = 0; i < 10; i++) {
$('select').prepend('<option>' + (i + 1) + '</option>');
}
You can start at any given starting value by simply adding that number to the current loop-set index value.
$.each(( index ) => {
index += 1 //or any other starting value
// your code
});
You can't. Why not just declare another variable at the first line of the function var myIndex = index + 1;
?