TAG
JavaScript
Result
Run
License
<label><input type="checkbox" name="fruits" value="Apple" />Apple</label> <label><input type="checkbox" name="fruits" value="Banana" />Banana</label> <label><input type="checkbox" name="fruits" value="Carrot" />Carrot</label> <label><input type="checkbox" name="fruits" value="Durian" />Durian</label>
document.addEventListener("DOMContentLoaded", () => { const $elFruits = document.querySelectorAll("input[name='fruits']"); let aFruits = []; $elFruits.forEach(elInput => { elInput.addEventListener("click", e => { let elTarget = e.currentTarget; if(elTarget.checked) { aFruits.push(elTarget.value); } else { let delIdx = aFruits.indexOf(elTarget.value); if(delIdx > -1) aFruits.splice(delIdx, 1); } console.log(aFruits.join(", ")); }); }); });
Console
expand_less
License
License
by DevDic
Close