skip to Main Content
function boxes() {
  let body = document.querySelector("body");
  let todoLabel = document.createElement("label");
  //
  let priorityHigh = document.createElement("input");
  priorityHigh.type = "radio";
  priorityHigh.value = "High";
  priorityHigh.name = "radio";
  //
  let priorityMedium = document.createElement("input");
  priorityMedium.type = "radio";
  priorityMedium.value = "Medium";
  priorityMedium.name = "radio";
  //
  let priorityLow = document.createElement("input");
  priorityLow.type = "radio";
  priorityLow.value = "Low";
  priorityLow.name = "radio";

  todoLabel.appendChild(priorityHigh);
  todoLabel(priorityMedium);
  todoLabel.appendChild(priorityLow);
  body.appendChild(todoLabel);
}




function getValue() {
  let priorityInput = document.getElementsByName("input[type='radio'][name=radio]").value;

  let button = document.createElement("button");
  document.body.appendChild(button);

  button.addEventListener("click", () => {
    console.log(priorityInput);
  });
}

So im expecting to get the the value of whatever radio button is clicked, say I clicked the first one, I would expect to get the value of "High" or if I decide to click the second one then I expect to get the value of "Medium" but I get back null

2

Answers


  1. Try out:

    let priorityInput = document.querySelector('input[type="radio"][name="radio"]:checked').value;
    

    This should select the first checked radio button with the name "radio" and save the value in the "priorityInput" variable.

    Login or Signup to reply.
  2. I use the suggestion from @Dusto to find a solution for you:

    The source of your trouble is placed into the function getValue(). You have to just replace and move line *1 :

    function getValue() {
      
      //*1 also misplaced
      //  let priorityInput = 
      //  document.getElementsByName("input[type='radio'][name=radio]").value;
    
      let button = document.createElement("button");
      document.body.appendChild(button);
    
      button.addEventListener("click", () => {
            //moved and replaced
             let priorityInput = 
                document.querySelector('input[name="radio"]:checked').value;
            console.log(priorityInput);
      });
    }
    

    Additional, for a good behaviour you schould check the value priorityInputto null in case no selection has being made.

    Also there is a small error in boxes(): The line todoLabel(priorityMedium); still needs .appendChild.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search