You are using the Array.prototype.map()
function to create an array with transformed values. That's fine. But you want to include only values where the corresponding checkbox is checked. You can do that by adding a call to the Array.prototype.filter()
function.
There are multiple ways to do this. One of the easiest solutions would be to first call map()
to create an array with items containing the checkbox values and the corresponding number values, then use filter()
to create an array with only the checked items, and then use map()
again to get an array with the resulting number values. Something like this:
let olist =
[...document.querySelectorAll('table tbody tr')]
.map(row => {
const children = row.querySelectorAll('input');
return {
checked: children[0].checked,
value: parseInt(children[1].value)
}
})
.filter(item => item.checked)
.map(item => item.value)
document.getElementById('final').innerHTML = olist.join(', ')
Note that you can probably omit the parseInt
call inside the first map
callback function as well, because afterwards you are just concatenating those values into a string again.
Edit
An even shorter alternative would be something like this:
let olist =
[...document.querySelectorAll('table tbody tr')]
.filter(row => row.querySelector('input[type=checkbox]').checked)
.map(row => row.querySelector('input[type=number]').value)
document.getElementById('final').innerHTML = olist.join(', ')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…