【发布时间】:2016-06-10 15:06:20
【问题描述】:
我有一个产品列表,每个单独的产品都有一个带有产品 ID 的复选框值,例如“321”。检查产品复选框(可以超过1个选定),我需要收集的值。每个产品还将有一个用于定义数量的输入文本字段,例如“23”,我还需要收集此数量值。只有选中复选框,QTY文本值大于1.计划是收集所有这些对象,将它们放入循环,最后将它们转换为我可以的字符串显示结果。
到目前为止,我已经设法收集复选框值并将它们放入一个字符串中,但我不确定如何在不破坏它的情况下收集附加文本 Qty 输入值。我的理解是 document.getElementsByTagName('input') 能够收集两种输入类型,因为它基本上是在寻找输入标签,所以我只需要弄清楚如何收集和循环通过复选框和文本输入。
有人建议我使用 2 个 if 语句来完成此操作,但我是学习 javascript 的新手,所以我不完全确定如何去做。我确实尝试在第一个语句的正下方添加 if 语句(就像在 php 中那样),但这似乎完全破坏了它,所以我认为这是错误的。
到目前为止,这是我的工作代码,它收集复选框值并将它们放入字符串中。如果您选择复选框并按下按钮,则值将作为字符串返回。请注意,qty= 目前没有附加任何内容,因为我不知道如何收集和循环输入文本(这是我需要帮助的)。
如何收集额外的 qty 输入值并将此数字附加到 qty=
// function will loop through all input tags and create
// url string from checked checkboxes
function checkbox_test() {
var counter = 0, // counter for checked checkboxes
i = 0, // loop variable
url = '/urlcheckout/add?product=', // final url string
// get a collection of objects with the specified 'input' TAGNAME
input_obj = document.getElementsByTagName('input');
// loop through all collected objects
for (i = 0; i < input_obj.length; i++) {
// if input object is checkbox and checkbox is checked then ...
if (input_obj[i].type === 'checkbox' && input_obj[i].checked) {
// ... increase counter and concatenate checkbox value to the url string
counter++;
url = url + input_obj[i].value + '&qty=' + '|';
}
}
// display url string or message if there is no checked checkboxes
if (counter > 0) {
// remove first "&" from the generated url string
url = url.substr(1);
// display final url string
alert(url);
}
else {
alert('There is no checked checkbox');
}
}
<ul>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="311">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="321">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" id="checked-product" name="checked-product" value="98">Add To Cart
<div class="quantity">
<input type="text" name="qty" id="qty" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="javascript:checkbox_test()">Add selected to cart</button>
【问题讨论】:
-
您不是在
+ '&qty=' + '|';的字符串中添加数量吗?也许这就是问题所在。 -
是的,这就是问题所在,但我不知道如何收集和计算复选框和文本输入值而不破坏它。
-
input_obj将包含checkbox和text元素,因此您的 for 循环中可以有 2 个 if 语句,当它是checkbox时,添加product=和当它是text时,添加您的 URL 的qty=部分。 -
我想这并不能解决知道什么时候应该或不应该添加
qty=基于复选框选中或未选中的问题...... -
你有没有研究过这个问题的 jQuery 解决方案?
标签: javascript html checkbox input