此脚本从复选框中提取数据以确定表单发送到 PayPal 的信息。 Paypal 只接受没有任何间隙的购物车;但是,此脚本会计算索引中未选中的框,这会使购物车无效(“item_name_1”、“item_name_3”、“item_name_7”)。如何使脚本生成连续的数字(“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;
}
最佳答案
除了编号之外,您的代码还有一些问题:
该函数有一个从未使用过的 form
参数。
document.getElementById()
返回单个 DOM 元素或 null。您的 P
变量是一个 jQuery 对象,假设您按 id 选择,它应该包含一个元素或没有 - 假设您正在尝试将 P
与您似乎认为它可能有多个匹配元素,但只有当你有多个具有相同 id 的无效 html 元素时才会这样(这将给出不可靠的结果 - 所以如果是这样你应该修复它:你可以使用相同名称的元素,但不是相同的 ID)。
无论哪种方式,尝试将 P 用作 .getElementById()
返回的 DOM 元素的属性都没有任何意义。所以无论你说什么 document.getElementById('').P.something
都是错误的。
就为隐藏输入生成唯一编号而言,您只需要一个循环计数器变量i
,然后是第二个(新)变量用于输入计数,我们称它为n
。仅在 if checked
语句中增加 n
。或者,如果您使用 jQuery 进行循环,则不需要 i
,只需 n
。如果您显示您的 HTML,我可以正确地更新它而不是猜测,但是像这样:
function updateCart(form) {
// first remove any hidden inputs from a previous unsuccessful submit
// (this may be optional depending on whether you're submitting with ajax
// and/or potentially aborting the submit for other reasons, e.g., if you're
// submitting with ajax and the web server might return an error you need to
// remove the previous hiddens if the user tries again)
$('#cart_items input[type="hidden"]').remove();
// now process each checkbox and add numbered elements for each checked one
var n = 0,
$f = $("#cart_items");
// you may need to vary the selector here because
// I don't know the names of your elements
$('input[type="checkbox"]').each(function() {
if (this.checked) {
// following is a tidied up version of your input creation code,
// which assumes that the value attribute of the checkbox holds
// the item name and price information.
n++;
$f.append('<input type="hidden" name="item_name' + n +
'" value="' + this.value.substring(6) + '">');
$f.append('<input type="hidden" name="amount_' + n +
'" value="' + this.value.substring(0,5) + '">');
}
});
if (n === 0) {
// no hiddens were added
alert("Please select products");
return false;
} else {
// success, inputs added above
return true; // or submit or whatever
}
}
关于javascript - 选中框脚本正在计算索引中未选中的框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8686066/