Skip to content
CoursesWeb Forum

How do I get the value of the selected radio button in JavaScript

Needs an answerAsked by Odalys F. · JavaScript and the DOM0 replies

Short answer

I am building a tiny quiz page for my coding club. Each question has three radio buttons and a Check button. I tried this:

Written by Odalys F. ·
CiteCoursesWeb Forum, "How do I get the value of the selected radio button in JavaScript", https://coursesweb.net/forum/t/how-do-i-get-the-value-of-the-selected-radio-button-in-javascript/, accessed 2026-12-01.
  1. Member ·
    <input type="radio" name="q1" value="paris"> Paris
    <input type="radio" name="q1" value="rome"> Rome
    <input type="radio" name="q1" value="madrid"> Madrid
    <button id="check">Check</button>
    
    document.querySelector("#check").addEventListener("click", () => {
      const answer = document.getElementsByName("q1").value;
      console.log(answer);
    });
    

    The console prints undefined whatever I pick. One of my students said "loop through them", but that seems like a lot of code for twelve year olds. Is there a short, readable way to get the one that is ticked, and what should happen when nobody has picked anything yet?

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

No answers yetOdalys F. is waiting. If you have seen this before, a two-line answer helps.
Write an answer
CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.