This script extracts data from check boxes in order to determine the information a form sends to PayPal. PayPal only accepts a cart without any gaps; however, this script counts unchecked boxes in the index which makes the cart invalid (“item_name_1”, “item_name_3”, “item_name_7”). How do I make it so that the script generates a gapless succession of numbers (“item_name_1”, “item_name_2”, “item_name_3”)?
function updateCart(form) {
var cart = "";
var P = $('#P');
for (var i = 0; i < document.getElementById('sList').P.length; i++) {
if (document.getElementById('sList').P[i].checked)
cart += '<input type="hidden" name="item_name_' + (i+1) + '" value="' + document.getElementById('sList').P[i].value.substring(6) + '"><input type="hidden" name="amount_' + (i+1) + '" value="' + document.getElementById('sList').P[i].value.substring(0, [5]) + '">'
}
if (cart == "") {
alert("Please select products")
} else alert(cart);
$('#cart_items').html("" + cart);
return false;
}
Your code has a few issues aside from the numbering:
The function has a
formparameter that is never used.document.getElementById()returns either a single DOM element or null. YourPvariable is a jQuery object that, given you are selecting by id, should hold one element or none – given you are trying to usePwith an index you seem to think it could have multiple matching elements but that would only be if you’ve got multiple elements with the same id which is invalid html (which will give unreliable results – so if so you should fix it: you can elements with the same name, but not the same id).Either way it doesn’t make any sense to try to use P as a property of the DOM element returned by
.getElementById(). So everywhere that you saiddocument.getElementById('').P.somethingis wrong.As far as generating unique numbering for the hidden inputs, you just need one variable for the loop counter,
i, and then a second (new) variable for the input counting, let’s call itn. Incrementnonly within theif checkedstatement. Or if you loop with jQuery you don’t needi, justn. If you show your HTML I could update this properly rather than guessing, but something like this: