javascriptdominnerhtmlgetelementbyidgetelementsbyname

Get radio buttons values and add to innerHTML script


I have a form that has text, drop downs and radio buttons. I have a script that then grabs the values and displays the values in a text area field. I can grab the values for the text and drop downs but the radio buttons always return either an Undefined error or object nodelist error. Here is sample code of what I'm doing inside form tags:

<form>
<input type="text" id="name" onChange="mySummary();" />
<input type="text" id="phone" onChange="mySummary();" />
<input type="radio" name="contact" value="Spoke with" onChange="mySummary();" />
<input type="radio" name="contact" value="left voicemail" onChange="mySummary();" />
<input type="text" id="moreinfo" onChange="mySummary();" />
<textarea id="Summary" rows="10" cols="30"></textarea>
</form>

I then call the data in my JavaScript as follows:

function mySummary() {
var a = document.getElementById("name").value;
var b = document.getElementById("phone").value;
var c = document.getElementsByName("contact").value;
var d = document.getElementById("moreinfo").value;
document.getElementById("Summary").innerHTML = 
"Name: " + a + "\n" +
"Phone: " + b + "\n" +
"Contacted How: " + c + "\n" +
"Additional information" + d;
}

When I try to use the above I get undefined message doe the radio options.

How do I pull the values of what was selected for the radio buttons and that the value changes to the new selection by the user the output changes as well. I've searched but haven't found one that is used in the innerHTML with other ids


Solution

  • You can loop over all the radio buttons in the radio button group with name contact and check which radio button is checked. Then, set the value of that radio button in variable c:

    function mySummary() {
      var a = document.getElementById("name").value;
      var b = document.getElementById("phone").value;
      var radioBtn = document.getElementsByName("contact");
      var c;
      for(i=0; i<radioBtn.length; i++){
       if(radioBtn[i].checked){
         c = radioBtn[i].value;
       }
      }
      
      var d = document.getElementById("moreinfo").value;
      document.getElementById("Summary").innerHTML = 
      "Name: " + a + "\n" +
      "Phone: " + b + "\n" +
      "Contacted How: " + c + "\n" +
      "Additional information" + d;
    }
    <form>
    <input type="text" id="name" onChange="mySummary();" />
    <input type="text" id="phone" onChange="mySummary();" />
    <input type="radio" name="contact" value="Spoke with" onChange="mySummary();" />
    <input type="radio" name="contact" value="left voicemail" onChange="mySummary();" />
    <input type="text" id="moreinfo" onChange="mySummary();" />
    <textarea id="Summary" rows="10" cols="30"></textarea>
    </form>