Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get checkbox value on submit

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

like image 971
Kevin.a Avatar asked Jul 23 '26 18:07

Kevin.a


2 Answers

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>
like image 169
31piy Avatar answered Jul 26 '26 07:07

31piy


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>
like image 45
marmeladze Avatar answered Jul 26 '26 08:07

marmeladze