Hi I'm new to web development and working on simple projects and I am stuck on a problem if anyone can help. I have a 3 checkboxes that a user can check on what their favourite things are to do. After completing the question I am trying to log the value of the chosen boxes however I am getting unidentified results if anyone can help id be grateful. This is the code: html:
What is your favorite thing to do:
<p id = "favoriteThings">
<input type="checkbox" name="TV" value=1>Watch TV
<input type="checkbox" name="Books" value=2>Read Books
<input type="checkbox" name="work" value=3>Work
</p>
JS:
var favoriteThings = document.getElementById("favoriteThings");
console.log("favorite things: " + favoriteThings.value);
I am assuming that the problem is the paragraph tag is the ID but can someone give me a fix to this? As I don't want to give each checkbox the same ID as I heard its bad practice. thanks in advance.
name for your group of inputsvalue"[]""input" in your case:const ELs_favorite = document.querySelectorAll("[name=favorite]");
const get_favorite = () => {
const checked_values = [...ELs_favorite].reduce((arr, EL) => {
if (EL.checked) arr.push(EL.value);
return arr;
}, []);
console.log(checked_values);
};
ELs_favorite.forEach(EL => {
EL.addEventListener("input", get_favorite);
});
What is your favorite thing to do:
<p>
<label><input type="checkbox" name="favorite" value="tv">Watch TV</label>
<label><input type="checkbox" name="favorite" value="books">Read Books</label>
<label><input type="checkbox" name="favorite" value="work">Work</label>
</p>
In the example above, Array.reduce() is used to collect only the values of the checked input elements into an Array.
you can give each checkbox the same id (there is no problem).
Solution:
<p id = "favoriteThings">
<input type="checkbox" name="favoriteThings" value="TV" or "1" onclick="MyNameFunction()">Watch TV
<input type="checkbox" name="favoriteThings" value="Read Books" or "2" onclick="MyNameFunction()">Read Books
<input type="checkbox" name="favoriteThings" value="Work" or "3" onclick="MyNameFunction()">Work
</p>
js
var choices = [];
var els = document.getElementsByName('favoriteThings');
console.log("Favourite things: ");
for (var i=0;i<els.length;i++){
if ( els[i].checked ) {
console.log(els[i].value);
}