Display information based on the radio button chosen

I've set up a radio button with options for "no" and "yes", but neither is selected by default.

Here's what I'm trying to achieve: If someone selects "no", nothing should happen. However, if they select "yes", then a message saying "hello world" should be displayed below the radio buttons.

Could anyone provide some assistance?

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

Answer №1

To handle clicks on the radio buttons, you must set up event listeners. When a button is clicked, check its value. If it's "yes", display "hello world"; otherwise, leave the message blank:

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>

If you prefer using jQuery, here's an alternative solution:

$(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>

Answer №2

To make something happen on a click event, simply attach an event listener to the element in question:

A Vanilla JavaScript approach:

document.querySelector('input[value="charge"]').addEventListener("click", function()
{
    document.getElementById("someId").innerHTML += "HELLO WORLD!<br>";
});
<input type="radio" name="myRadio" value="no-charge">
No
<input type="radio" name="myRadio" value="charge">
Yes
<p id="someId"></p>

Using JQuery for a solution:

$('input[value="charge"]').click(function()
{
    $("#someId").html($("#someId").html() + "HELLO WORLD!<br>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="radio" name="myRadio" value="no-charge">
No
<input type="radio" name="myRadio" value="charge">
Yes
<p id="someId"></p>

Answer №3

To implement an event listener, use the following code:

document.getElementById("yes").addEventListener("click", () => console.log("Hello world!"));
<form>
  <input type="radio" value="no-charge"> No
  <input type="radio" value="charge" id="yes"> Yes
</form>

Answer №4

1.Method

  let radio_1 = document.getElementById("radio_1")
  radio_1.addEventListener("click",function(){
    alert("hello world")
  })
  <input type="radio" value="no-charge" id="radio_1">
  <input type="radio" value="charge" id="radio_2">

2.Approach

    function myAlert(){
      alert("hello world")
    }
  <input type="radio" value="no-charge" onclick=myAlert()>
  <input type="radio" value="charge" id="radio_2">

3.Strategy

    $("#radio_1").click(function(){
      alert("hello world")
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" value="no-charge" id=radio_1>
  <input type="radio" value="charge" id="radio_2">

Answer №5

function updateDisplay(event) {
  var message = document.getElementById("hello-world");
  console.log(event.target.value);
  if(event.target.value === "yes"){
    message.style.display = "block";
  } else { 
    message.style.display = "none";
  }
}
<input type="radio" name="options" value="no" onchange="updateDisplay(event);">
No
<input type="radio" name="options" value="yes" onchange="updateDisplay(event);">
Yes
<div id="hello-world" style="display:none">Hello World</div>

Answer №6

<input name="query" value="yes" id="radioY" type="checkbox"> Yes
<div id="msg"></div>

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

function init() {
  radioQuery[0].addEventListener("click", verifyClicked);
  radioQuery[1].addEventListener("click", verifyClicked);
}
//
function verifyClicked() {
  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.onload = init();
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When exporting data from Datatable to Excel, decimal values including the % symbol may experience rounding issues

I am facing an issue when trying to export a Datatable to an excel sheet. The column in the Datatable contains decimal values with a % symbol. However, after exporting, the decimal values are being rounded off. I need the decimal values along with the % sy ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

Avoid creating a line break directly after the header, however allow for a line break

I find myself in a scenario where I require a paragraph that has a specific format: An Emphasized Title Some relevant information regarding the subject... I am looking to insert a new line before the title, ensuring it seamlessly integrates with the re ...

Navigate through each of the pictures within the folder and encode them into base64

I'm currently working on a project where I need to convert images in a folder to base64 and then store them in MongoDB. At first, I successfully converted a single image: var filename = '1500.jpg'; var binarydata = fs.readFileSync(filename ...

Tips for using various versions of jQuery at the same time

Despite searching on Stack Overflow, none of the answers provided seem to work for my issue. My requirement is to utilize two separate versions of jQuery. Below is the code snippet: I first link to the initial version and use the following code: <sc ...

Conceal picture when clicked

My goal is to hide an image upon clicking and then show it again by clicking a specific tag. I've attempted various codes, but none have been successful. Every time I click, the image continues to add to the page. <body> <a href="#" class= ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

Having difficulty updating the state with editorState retrieved from the server in ReactJs when using draftJs

Incorporating a rich text editor into React using draftJs has been successful. The editorState data is converted to raw data, stringified, and sent to the server for rendering on the front end. However, I am facing challenges in updating the editorState ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

Lists within lists and the use of percentages

There is a common belief that separating design and functionality is beneficial. Let's focus on the separation between HTML and CSS, specifically when organizing a menu hierarchy. The issue with nested <ol>, <ul>, and <li> elements ...

What is the best approach to extracting tightly-coupled code and converting it into an external library?

I have a question regarding paradigms that I would like to address, and if this is not the appropriate platform, please guide me to the right place. Your recommendations are most welcome :) Currently, I am tasked with extracting a significant piece of fun ...

Implementing Jquery tabs to load content using Ajax as the user scrolls the page

I'm implementing AJAX to load content in jQuery tabs and I want to continuously load more content from the active tab's URL and append it to the list, similar to how it works on Facebook. Is there a way to combine loading content while scrolling ...

By utilizing the <tr> element, one can enhance the border thickness by 1 pixel

Is it possible to ensure that row selection in a table is consistent in terms of border alignment on both sides? https://i.stack.imgur.com/qmZiQ.png If you have any suggestions or solutions, please share them. Thank you! table { margin: 10px; bord ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

Ensure that the input box expands to occupy the entire HTML page

After reviewing numerous pages and questions related to this topic, I have located the correct solution but am struggling to implement it. My goal is to achieve a similar outcome to the second question, but I'm having difficulty figuring out how to do ...

Using Selenium to determine the quantity of elements that have a similar class present

Here is the test code I am using: it('count elements by class', async t => { let count = await driver.findElements(By.css('my-questions-class')).then(v => v.length); assert.equal(count, 3); // The count should b ...

Can a JavaScript function spontaneously run without being called upon?

<a onclick="determineCountry(data)" class="installbtn">Install</a> My goal is to have the user redirected to one of three sites based on their location when they click the button above. However, there seems to be an issue with the script below ...

Request for a new login using credentials via ajax

We've set up a web application on a LAMP(PHP) system that makes around 40 Ajax calls. Users are tracked using PHPSessions with a 1 hour cookie lifespan (which we want to maintain for quick expiration). ISSUE: If a user is inactive for the full hour an ...