Stack Overflow Asked by Afelip on December 25, 2021
I need to get all checked values from checkboxes and return them in element.
I have a code:
this.values = [];
if (item.checked) {
this.values.push(item.value);
} else {
this.values.splice(item.value)
}
return alert(this.values);
There are few problems:
(this.values = [1,1,1])
(this.values = []);
What I need is:
if I have item values for example: 1 , 2 , 3
And check every item, that my array will become – this.values = [1 , 2 , 3]
If I uncheck item number 2, this.values = [1, 3]
since you didn't show your html file. I just posted the code works for me for your reference.
function getSelectedCheckboxValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
let values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
return values;
}
if you are editing js in the HTML, replace
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
with
const checkboxes = document.querySelectorAll('input[name="color"]:checked');
source: https://www.javascripttutorial.net/javascript-dom/javascript-checkbox/
Answered by Gniu on December 25, 2021
Ciao, you can do this:
this.values = [];
if (item.checked) {
if(!this.values.includes(item.value)) {
this.values.push(item.value);
}
} else {
if(indexOf(item.value) !== -1){
this.values.splice(this.values.indexOf(item.value), 1)
}
}
return alert(this.values);
Insert item.value
only if this.values
does not contains value and use splice
with index (if item is in this.value
).
Answered by Giovanni Esposito on December 25, 2021
Use a common class for all the checkbox, then use document.querySelectorAll
to get the checkbox and attach event listener to each of the box.
Now on change
even call another function and first filter
out the checked
checkbox then use map
to get an array of the check box value
let elem = [...document.querySelectorAll('.checkBox')]
elem.forEach(item => item.addEventListener('change', getChecked))
function getChecked() {
let getChex = elem.filter(item => item.checked).map(item => item.value)
console.log(getChex)
}
<input type="checkbox" value="1" id="one" class="checkBox">
<label for="one">1</label>
<input type="checkbox" value="2" id="two" class="checkBox">
<label for="two">2</label>
<input type="checkbox" value="3" id="three" class="checkBox">
<label for="three">3</label>
Answered by brk on December 25, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP