Home > Software design >  checkbox value unidentified
checkbox value unidentified

Time:12-08

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.

CodePudding user response:

  • When you want to group your checkbox (or radio) inputs, use the same name for your group of inputs
  • Use a different value
  • Use querySelectorAll() to get your desired elements using the Attribute selector "[]"
  • Use nodeList.forEach() to iterate your elements
  • Use addEventListener() to attach an Event, "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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In the example above, Array.reduce() is used to collect only the values of the checked input elements into an Array.

CodePudding user response:

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);
    }
  • Related