0

My problem is I am trying to show what is entered into the form right below the form, and for some reason, my radio button comes back as undefined.

I tried putting an id in the radio button itself but that didn't turn out well. It just says the first in the list of radio buttons then. Code that I am using:

function myFunction(){
  document.getElementById("HideOrShow").innerHTML = " SID: " + document.getElementById('sid').value + "<br>"
    + "First Name: " + document.getElementById('fname').value + "<br>"
    + "Last Name: " + document.getElementById('lname').value + "<br>"
    + "Major: " + document.getElementById('Major').value + "<br>"
    + "Advisor: " + document.getElementById('advisor').value + "<br>"
    + "New Student?: " + document.getElementById('checkbox').value + "<br>"
    + "Enrollment Date: " + document.getElementById('date').value;
}
<fieldset>
    <legend id="advisor">Advisor </legend>
    <input type="radio" name="Advisor" value="Chris_McCarthy">Chris McCarthy<br>
    <input type="radio" name="Advisor" value="Karen_Smith">Karen Smith<br>
</fieldset>

I need it to show the advisor's name that was chosen

Samuel
  • 422
  • 3
  • 11

2 Answers2

1

You can get the value of the radio button by following the code.

function onRadioChange() {
  console.log(document.querySelector('input[name="Advisor"]:checked').value);
}
<fieldset>
    <legend id="advisor">Advisor </legend>
    <input type="radio" name="Advisor" value="Chris_McCarthy" onchange="onRadioChange()">Chris McCarthy<br>
    <input type="radio" name="Advisor" value="Karen_Smith" onchange="onRadioChange()">Karen Smith<br>
</fieldset>
Samuel
  • 422
  • 3
  • 11
0

If you're not using jQuery, you can figure out which radio button is selected by getting their DOM handler with getElementById() and grabbing the "checked" property.

Check the following example:

function myfunction() {
  var divResult = document.getElementById("result");
  var a1 = document.getElementById("a1");
  var a2 = document.getElementById("a2");
  if (a1.checked) {
    divResult.innerHTML = a1.value;
  } else {
    divResult.innerHTML = a2.value;
  }
}
<fieldset>
  <legend id="advisor">Advisor </legend>
  <input type="radio" id="a1" name="Advisor" value="Chris_McCarthy">Chris McCarthy
  <br>
  <input type="radio" id="a2" name="Advisor" value="Karen_Smith" checked>Karen Smith
  <br>
</fieldset>

<button  onclick="myfunction()">Clickme</button>
<div id="result"></div>

Notice that I also set a default option using the "checked" attribute, otherwise, I would have to handle an "if"-"else if"-"else" condition to handle the case when no option is selected.

DanyAlejandro
  • 1,440
  • 13
  • 24