Lets say I have a form with a few checkboxes. Whenever i submit that form i want all the values of the selected checkboxes to be printed.
<form>
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product2" name="product1" value="13">
<input type="checkbox" id="product3" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
The usecase for this is as follow:
I have a webshop, i want to add multiple products to my cart at once.
I have a link which is the basic and looks like : test.com/addtocart? After the questionmark i need to add the values of the checkboxes separated by comma's. For example if the value 12 and 14 are selected it should generate a link like this: test.com/addtocart?12,14
Here is a way to do that. You can loop through the checkboxes and print the values if checkboxes are checked.
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const values = Array.from(document.querySelectorAll('input[type=checkbox]:checked'))
.map(item => item.value)
.join(',');
console.log(`test.com/addtocart?${values}`);
});
<form>
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product1" name="product1" value="13">
<input type="checkbox" id="product1" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
A vanilla js solution might be like that.
document.querySelector("button").addEventListener('click', function(e){
e.preventDefault();
var form = document.querySelector("form");
Array.from(form.querySelectorAll("input")).forEach(function(inp){
if(inp.checked === true) { console.log(inp.value); }
});
});
<form>
<input type="checkbox" id="product1" name="product1" value="12">
<input type="checkbox" id="product2" name="product1" value="13">
<input type="checkbox" id="product3" name="product1" value="14">
<button type="submit">Subscribe</button>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With