JSFiddle - React, Tailwind, and code Playground
HTML
<ul>
<li>
<form>
<input type="checkbox" name="checked-product" value="311">Add To Cart (311)
<div class="quantity">
<input type="text" name="qty" data-product-id="311" maxlength="12" value="1" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" name="checked-product" value="321">Add To Cart (321)
<div class="quantity">
<input type="text" name="qty" data-product-id="321" maxlength="12" value="10" class="input-text qty"/>
</div>
</form>
</li>
<li>
<form>
<input type="checkbox" name="checked-product" value="98">Add To Cart (98)
<div class="quantity">
<input type="text" name="qty" data-product-id="98" maxlength="12" value="5" class="input-text qty"/>
</div>
</form>
</li>
</ul>
<button type="button" onclick="checkbox_test()">Add selected to cart</button>
<div id="output">
</div>
CSS
#output {
margin-top: 10px;
}
JavaScript
// 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
checkboxes = document.getElementsByName('checked-product'),
qtyBoxes = document.getElementsByName('qty'),
checkedBoxes = {},
pid;
// loop through all collected objects and gather the checked boxes
for (i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
counter++;
checkedBoxes[checkboxes[i].value] = 1; // update later w/ real qty
}
}
// now get the entered Qtys for each checked box
for (i = 0; i < qtyBoxes.length; i++) {
pid = qtyBoxes[i].getAttribute('data-product-id');
if (checkedBoxes.hasOwnProperty(pid)) {
checkedBoxes[pid] = qtyBoxes[i].value;
}
}
// now build our url
Object.keys(checkedBoxes).forEach(function(k) {
url += [
k,
',qty=',
checkedBoxes[k],
'|'
].join('');
});
url = url.replace(/\|$/, ''); // remove trailing |
// 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');
}
}