I’m trying to generate form elements with jQuery to send to a Paypal form, I’m having issues looping through an array.
The list of items in a shopping cart is held in an array, the Javascript loops through the array adding the form fields and values as follows
for (j=0;j<(itemArray.length);j++)
$('#createFields').append("<input type='hidden' name='item_name_"+ j +"' value='"+itemArray[j]+"'/>");
This works perfectly, except, I need item_name_ to begin with a 1, not a 0.
“easy” I thought
for (j=0;j<(itemArray.length);j++)
$('#createFields').append("<input type='hidden' name='item_name_"+ j+1 +"' value='"+itemArray[j]+"'/>");
Should work, but no, that gives 01.
So I figured it wasn’t treating “j” as integer
So I tried
(j*1)+1
That still gave me 01
parseInt(j)+1
Also gives me 01!
How can I get “0+1 = 1” from this counter variable?!
I can’t understand why this issue is happening, I’ve got over the same problem with the methods above many times before!
I’ve also tried
for (j=1;j<( (itemArray.length+1) );j++)
but that just screws up the looping
Just group the expression:
this will give
j + 1a higher precedence so that it is evaluated first and then concatenated.Otherwise, concatenation with the string will take place first, that is, first
jis concatenated with the preceding string and then the resulting string is concatenated with1(left to right evaluation). Without grouping, the expression is implicitly evaluated as: