Show text on a radio button selection

Issue

I have created a radio button which says “no” and “yes”. By default, nothing is selected.

So what I’m looking to do here is, if someone select no, nothing happens, but if someone select “Yes” It should print a text below saying hello world.

Can someone help?

<input type="radio" value="no-charge">
No
<input type="radio" value="charge">
Yes

Solution

You need to set up event listeners for clicks on the radio buttons. When either is clicked, you need to check the value of the checked button. When it’s “yes”, set your message to “hello world”, and blank when it’s “no”:

var radioY = document.getElementById("radioY");
var msg = document.getElementById("msg");
var radioQuery = document.getElementsByName("query");

function start() {
  radioQuery[0].addEventListener("click", checkClicked);
  radioQuery[1].addEventListener("click", checkClicked);
}
//
function checkClicked() {
  for (var x = 0; x < radioQuery.length; x++) {
    if (radioQuery[x].checked && radioQuery[x].value == "yes") {
      msg.innerHTML = "Hello World";
      return;
    } else {
      msg.innerHTML = "";
    }
  }
}
//
window.load = start();
<input name="query" value="no" type="radio"> No
<input name="query" value="yes" id="radioY" type="radio"> Yes
<div id="msg"></div>

Here’s a jQuery solution you might prefer:

$(document).ready(function() {
  $("#radioY").click(function() {
    $("#msg").text("Hello World!");
  });
  $("#radioN").click(function() {
    $("#msg").text("");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='radio' id='radioN' name='query' value='no' /> No
<input type='radio' id='radioY' name='query' value='yes' /> Yes
<div id="msg"></div>

Answered By – MichaelvE

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.