I've got the following function that gets all checked checkboxes on my html form with the given element Name. I have a loose understanding that a reduce function can replace the .map and .join sections so was looking for a poke in the right direction of how to implement that and also if there is any other steps I could take to optimise this function?
function getCheckedValuesOf(elmName){
return [...document.getElementsByName(elmName)].filter(box=>box.checked==true).map(box=>box.value).join(", ")
}
function getCheckedValuesOf(elmName) {
return [...document.getElementsByName(elmName)]
// acc is value returned by previous iteration
// curr is the current iterated element
.reduce((acc, curr) => {
// do nothing on unchecked
if (curr.checked) {
// add a , only if acc is not empty, to prevent useless starting ,
acc += (acc !== "" ? ", " : "") + curr.value
}
// always return acc, or next iteration will have acc === undefined
return acc;
// second argument of reduce is the initial value of acc
// if not set then it default to the first element of the array
// and the iteration starts on the second element
}, '')
}
document.getElementById("log").onclick = () => console.log(getCheckedValuesOf("name"))
console.log(getCheckedValuesOf("name"))
<input type="checkbox" name="name" checked="false" value="i1"/>i1
<input type="checkbox" name="name" value="i2"/>i2
<input type="checkbox" name="name" checked="false" value="i3"/>i3
<input type="checkbox" name="name" value="i4"/>i4
<input type="checkbox" name="name" checked="false" value="i5"/>i5
<input type="checkbox" name="name" value="i6"/>i6
<button id="log">log</button>
Can you try this one? Let me know if it works.
function getCheckedValuesOf(elmName) {
return [...document.getElementsByName(elmName)].reduce((a, b) => b.checked && b.value && (a.length>0 ? `${a}, ${b.value}`: `${a} ${b.value}`) || a, "");
}
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