【发布时间】:2016-12-27 11:12:44
【问题描述】:
我有一个表单,用户可以在其中输入详细信息并通过选中复选框来选择一个项目。
单击添加按钮时,检查项目值和存储在数组中的用户输入值,我在 url 中传递这些值。
用户可以添加多个具有不同名称和电子邮件的项目。假设我有三个项目,所以用户可以选择 item1 并填写 name1 和 email1 并单击添加按钮,类似地,如果他选择 item1 和 item2 并添加 name2 和 email2,他可以添加这些值。
每次点击时我都想检查项目 id 是否已经存在于数组中我不想添加它,只需增加数组中已经存在的该项目的数量并使用新数量更新数组
var allVals = []; //array where i am storing selected checkbox value
jQuery("#btnadd").click(function(event) { //on click of this button i am getting all values to construct url and pass this value to multi div from where i will validate my url
var qty;
jQuery(".selectitem:checked").each(function() {
qty = jQuery(this).next().find('input[name="quantity"]').val()); //getting quantity of selected checkbox its a input field
if (jQuery.inArray(jQuery(this).val(), allVals) == -1) {
allVals.push(jQuery(this).val() + ',' + qty); //item id not present in array so adding item id,qty in array
} else {
qty = qty + 1;
//here i would like to increase quantity of those items only which already present in array something like this.qty and update my allVal array with this new quantity
}
});
var rslt = allVals.join(';'); jQuery('#multi').val(rslt); //updating multi div value with allVals from here i will make redirect. Just want to pass correct values in that field
});
【问题讨论】:
-
你的 HTML 好吗?
-
所以问题在于更新数量对吗?此外,您将数据添加到数组中的方式效率不高。就像这种方法一样,您不知道哪个项目有什么数量
-
是的...只有数量更新...我的代码在不同的字符串中添加项目 id...如果我选择两次 item1 它在数组中添加 item1,1;item1,1 像这样但我想显示它 item1,2;以这种方式
-
你是不是只有数组?我可以建议一个更好的方法,我觉得会更容易处理
-
是的,一切都会好的
标签: jquery