I am trying to add the value of selected checkbox to anchor tag parameter "product-code" and "product-quantity". For example if someone click the first checkbox the product code parameter will be something like product-code="90;1" and product-quantity="1;1". And if someone also check the second checkbox the product code parameter will be like product-code="90;1;2" and product-quantity="1;1;1". Same for the third parameter. Can someone help me with this how I can get this done with the help of jquery?
<input type="checkbox" name="Apple" value="1">
<input type="checkbox" name="Banana" value="2">
<input type="checkbox" name="Orange" value="3">
<a href="#buy" product-code="90" product-quantity="1">Order Now!</a>
CodePudding user response:
its simple you just create two variables e.g productCode & productQuantity and place it anchor tag . Create a function to set upper variables value and execute this function on "onChange" event of checkbox .
here is the code :
<input type="checkbox" name="Apple" value="1">
<input type="checkbox" name="Banana" value="2">
<input type="checkbox" name="Orange" value="3">
<a href="#buy" product-code="90"
product-
quantity="1">Order Now!</a>
var productCode = "90";
var productQuantity = "1";
$("input[type=checkbox]").change(function(val){
productCode = productCode ";" val;
productQuantity = productQuantity ";" val;
});
CodePudding user response:
The following snippet should do the trick:
const a=document.querySelector("a");
const cbs=[...document.querySelectorAll("input[type=checkbox]")];
cbs.forEach(cb=>cb.addEventListener("click",ev=>{
a.setAttribute("product-code",[90,...cbs.filter(c=>c.checked).map(c=>c.value)].join(";"));
console.log(a);
}));
<input type="checkbox" name="Apple" value="1">
<input type="checkbox" name="Banana" value="2">
<input type="checkbox" name="Orange" value="3">
<a href="#buy" product-code="90"
product-
quantity="1">Order Now!</a>