How to get code of error when user not selected the radio button while submit the form?

Viewed 23

How to get the error code if the radio button is not selected on form submission? I am trying to get the button value from the Javascript DOM model. I get the value of the button but don't know how to error it out if the value is not found, but I can see the error in the console.

HTML

   <form action="/" id="RatingForm">
      <input type="radio" name="rating" id="btn-1" value="1" />
      <label for="btn-1">1</label>
      <input type="radio" name="rating" id="btn-2" value="2" />
      <label for="btn-2">2</label>
      <input type="radio" name="rating" id="btn-3" value="3" />
      <label for="btn-3">3</label>
      <input type="radio" name="rating" id="btn-4" value="4" />
      <label for="btn-4">4</label>
      <input type="radio" name="rating" id="btn-5" value="5" />
      <label for="btn-5">5</label>
      <input type="submit" name="" id="submit" />
   </form>

JS code:

      const form = document.getElementById("RatingForm");
      form.addEventListener("submit", (e) => {
        e.preventDefault();
        let button = document.querySelector("input:checked");
        if (button.value !== 0) {
          console.log(button);
        } else {
          console.log("error");
        }
      });

This is the error that I want to be displaying when the button value is not found.

index.html:75 Uncaught TypeError: Cannot read properties of null (reading 'value')
    at HTMLFormElement.<anonymous> (index.html:75:20)
1 Answers

That's because, in the if statement you checked for if(button.value !== 0) condition which means if the value is not equal to 0 then you are printing the button. And also, if the user is not clicking any button and submitting the form then the "button.value" will have null value. So, that is why you get "can not read null value" error.

Instead of checking your condition for if(button.value!==0), you should check for if (button) condition in your script.

form.addEventListener("submit", (e) => {
  e.preventDefault();
  let button = document.querySelector("input:checked");
  if (button) {
   console.log(button);
  }else {
   console.log("error");
  }
});

if(button) means if the user clicks on any button then only if statement will get executed or else the block will not run.

Related