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

Vue - Utilizing child slots in the render method

Within my component, I am working with a default slot and attempting to enhance the layout by wrapping each item in the slot within a div. However, I am facing an issue where I need to retrieve the classes of one of the slot elements, but the VNode element ...

Ways to detach event listener in Vue Component

One of my Vue2 components has a custom eventListener that I added in the mounted lifecycle hook. I am now trying to figure out the correct way to remove this listener when the component is destroyed. <template> <div> ... </di ...

Tips for aligning three <p> elements side by side using flexbox

I need assistance with aligning three boxes next to each other, each containing an image, header, and text. The issue arises when resizing the browser, causing the content in box 2 and 3 to be positioned higher than box 1. Below is the code I have been us ...

What is the method to display HTML code using JavaScript within a span element in a JSP page?

While working on a jsp file, I came across a span tag with the following code: <span id="divBasicSearchResults" style="height:100%;"></span> Below is the Javascript function that generates HTML content for this span: function renderBasicSear ...

Button background must be grayscale, while the text should remain unaffected

I have a variety of buttons with different background images. My goal is to apply a grayscale filter to the backgrounds by default and remove the filter on hover, without affecting the color of the button text. Currently, when I apply the grayscale filter ...

When using the require() function in Node.js, the period "." is not being recognized as part of the command and

I recently encountered a problem while working on my project and reorganizing my files. I noticed that the "." in my requires are not being parsed correctly. Upon running my program, an error message is displayed: Error: Module './src/map/createMa ...

Having trouble executing the command ~$ vue add unit-mocha using vue cli 3

I am trying to integrate mocha as a unit testing plugin into my existing Vue project, which was set up using CLI 3 (vue create myProj). This pertains to Vue CLI version 3.0.0 and above, in which my current project is operating. Here is the error message ...

Fill the center circle with GoJs background

Is there a specific way to paint the center circle only? I have provided an example project below. ...

Troubleshooting Tips: Removing a Specific Line from a Canvas Using Javascript

I need to find a method for removing a specific line without having to clear and redraw it. Learn more about clearing specific lines in Canvas with HTML5 I came across this question where everyone suggested clearing the entire page and redrawing it. Is t ...

Converting a Base64 URL to an image object: A step-by-step guide

I currently have a base64 URL in the following format: data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAA My objective is to convert this into an image file with the following properties: [File] 0: File lastModified: 1559126658701 lastModifiedDate: Wed M ...

How can Sequelize handle multiple foreign keys - whether it be for one-to-many relationships or many-to-many relationships

I'm working on a project with two tables: users and alerts. Users should have the ability to upvote and downvote on alerts. Here are the model definitions: Alert module.exports = function(sequelize, DataTypes) { var Alert = sequelize.define("al ...

"Learn the method for extracting the initial letter from a string with the help of

My knowledge of jQuery is limited. The script I'm using is shown below: var header = $('.time'+col).text(); alert(header); From the string "109:00AM", I need to extract the first letter, such as 1. Can someone please assist me with this? ...

After refreshing the page, vuex is encountering null values when using firebase.auth().onAuthStateChanged

Encountering an issue with Vuex and Firebase Authentication integration. When reloading the page, there is a delay in response from firebase.auth().onAuthStateChanged. I require an immediate response upon page reload without using router guards as seen in ...

What are the steps to downloading a server-generated image with user data from the client using Express?

I am facing a challenge with downloading a server-generated image immediately after it is created. My current approach involves using fetch to send user input data (bypassing HTML forms). Although the image is successfully generated on the server, I am str ...

Comparing the impact of class and element selectors on CSS performance

Considering that CSS is read from right to left, I am pondering the balance between performance and readability when it comes to adding classes to HTML in order to more efficiently target elements in CSS. Additionally, I am curious about how using a gener ...

Removing repetitive strings from an array in the most efficient manner

We've successfully developed a script to eliminate duplicate strings from an array while preserving the order necessary for angular's ng-repeat loop. It's also important that the remaining elements maintain their original index. scope.feedb ...

Is it advisable to avoid using `&apos;` for escaping single quotes?

According to the insights shared in conversations about the popularity of single quotes in HTML and Jquery embedded quote in attribute, the Wikipedia page on HTML highlights that: The use of the single-quote character ('), as a way to quote an attri ...

Having trouble with the vertical-align property in Google Chrome?

<html> <head> <style> table,td {border:1px solid black ;} table {width : 80% ;height:80%;} .top {vertical-align:top}; .center {vertical-align: middle}; .bottom {verti ...

Is there a bug in Firefox when using the multicolumn columns property with Flexbox?

Could this be a compatibility issue with Firefox? The layout appears fine in Chrome or when I take out columns: 2, then it also displays correctly in Firefox. div { width: 500px; padding: 2rem; display: inline-flex; align-items: baseline; bor ...

Is the JSON data missing from the POST request?

I'm having trouble inserting data into the database using a POST request. Here is how I'm making the request: 127.0.0.1:3000/api/users?fname=asd&lname=edc&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7870 ...