0

I'm a beginner and am trying to make the radio button submission generate the corresponding result below, fairly simple idea. Here's where I'm stuck

<h3>Choose Your Variable</h3>
<form action="#">
    <label for="itemtype"><input id="xmon" type="radio" name="monname" value="x">Xmon</label>
    <label for="itemtype"><input id="ymon" type="radio" name="monname" value="y">Ymon</label>
    <label for="itemtype"><input id="zmon" type="radio" name="monname" value="z">Zmon</label><br>
    <button type="submit">Submit</button> <button type="reset">Reset</button>
</form>

<p id="item">Your item is...</p>

<script>
    let answer = document.querySelectorAll("[name='monname']"); 
    let form = document.querySelector("form");

    form.addEventListener("submit", redirect);

function redirect() {
    event.preventDefault();
    if(answer.value == "x"){
        document.getElementById("item").innerHTML="Amon";
    }else if(answer.value == "y"){
        document.getElementById("item").innerHTML="Bmon";
    }else {
        document.getElementById("item").innerHTML="Cmon";
    }
}
</script>

On let answer = document.querySelectorAll("[name='monname']"); the final result is always "Cmon" no matter the radio button selected.
If I change it to let answer = document.querySelector("[name='monname']"); the result is always "Amon" no matter the radio button selected.

I have no idea what I'm missing. General code feedback is also appreciated.

Benny Yen
  • 98
  • 1
  • 7
  • 1
    Your `answer ` is `NodeList` . therefore, `answer.value` is `undefined` and that's why you always got `"Amon"` – Benny Yen Nov 19 '21 at 04:24
  • have a look: [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) – Benny Yen Nov 19 '21 at 04:24
  • 1
    And also check this out: [Radio group](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio#data_representation_of_a_radio_group). You can find the example. I think this is what you want – Benny Yen Nov 19 '21 at 04:31
  • As @BennyYen has mentioned, you will have to loop over the radio buttons and check who is checked, and then assign selected value to a variable and use this variable to check. You will find the reference code in accepted answer in original post – Rajesh Nov 19 '21 at 04:32

0 Answers0