Retrieve radio button value using JavaScript

Hey everyone, I'm struggling to retrieve the radio input value in my code. The alert is not triggering. I'm trying to create a real-time calculation feature that displays the total amount to pay, but I can't seem to handle the radio values properly. Any assistance would be greatly appreciated. Thanks! :D

function getRadioValue() {
    var vip = document.getElementsByName('mercedes');
    for (var i = 0; i < vip.length; i++) {
        if (vip[i].checked) {
            alert(vip[i].value);
            break;
        }
    }
}
<div class="form-group">
<label for="f1-about-yourself">Mercedes VIP transfer*:</label> <br>
<input type="radio" name="mercedes" id="yes" value="yes" onclick="getRadioValue()">
<label for="yes">Yes:</label>
&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="mercedes" id="no" value="no" checked="" onclick="getRadioValue()">
<label for="no">No:</label>
</div>

Answer №1

function retrieveSelection()
{
var car=document.getElementsByName('mercedes');
for (var i = 0, length = car.length; i < length; i++)
{
 if (car[i].checked)
 {
  
  alert(car[i].value);

  
  break;
 }
}

}
<div class="form-group">
<label  for="f1-about-yourself">Mercedes VIP selection*:</label> <br>
<input  type="radio" name="mercedes" id="yes" value="yes"
onclick="retrieveSelection()">
<label  for="yes">Yes:</label>
&nbsp;&nbsp;&nbsp;&nbsp;
<input  type="radio" name="mercedes" id="no" value="no"  onclick="retrieveSelection()">
<label  for="no">No:</label>
</div>📚

Answer №2

Aside from the solution already provided to fix the OP's issue, it's worth considering separating markup and code, avoiding inline code within HTML elements.

Utilizing the form element in HTML to contain specific form controls like input, button, etc. is highly recommended. Additionally, using the "DOM Level 0" form collection is still relevant. Event delegation, as shown in the following example, can be beneficial when dynamically adding new controls to a form, eliminating the need to register event handlers for each new control. Lastly, registering for 'change' events will capture every change made to the radio collection...

function isMercedesTransferType(elmNode) {
  return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
  var elmNode = evt.target;
  if (isMercedesTransferType(elmNode) && elmNode.checked) {
    console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
  }
}

function initializeVipTransfer() {
  document.forms['mercedes-vip-transfer'].addEventListener('change', handleVipTransferChange, false);
}

initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
  <legend>Mercedes VIP transfer*</legend>
  <label>
    <input  type="radio" name="mercedes" value="yes">
    <span>Yes</span>
  </label>
  <label>
    <input  type="radio" name="mercedes" value="no">
    <span>No</span>
  </label>
</form>

Another method of initializing necessary form controls directly is demonstrated below...

function isMercedesTransferType(elmNode) {
  return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
  var elmNode = evt.target;
  if (elmNode.checked) {
    console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
  }
}

function initializeVipTransfer() {
  var list = document.forms['mercedes-vip-transfer'].elements['mercedes'];
  Array.from(list).filter(isMercedesTransferType).forEach(function (elmNode) {
    elmNode.addEventListener('change', handleVipTransferChange, false);
  });
}

initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
  <legend>Mercedes VIP transfer*:</legend>
  <label>
    <input  type="radio" name="mercedes" value="yes">
    <span>Yes</span>
  </label>
  <label>
    <input  type="radio" name="mercedes" value="no">
    <span>No</span>
  </label>
</form>

...and to wrap things up, taking advantage of modern DOM queries with methods like querySelector and/or querySelectorAll in an "up to date" DOM can also be considered...

function handleVipTransferChange(evt) {
  var elmNode = evt.target;
  if (elmNode.checked) {
    console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
  }
}

function initializeVipTransfer() {
  var list = document.querySelectorAll('#mercedes-vip-transfer [type="radio"][name="mercedes"]');
  Array.from(list).forEach(function (elmNode) {
    elmNode.addEventListener('change', handleVipTransferChange, false);
  });
}

initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" id="mercedes-vip-transfer">
  <legend>Mercedes VIP transfer*:</legend>
  <label>
    <input  type="radio" name="mercedes" value="yes">
    <span>Yes</span>
  </label>
  <label>
    <input  type="radio" name="mercedes" value="no">
    <span>No</span>
  </label>
</form>

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

JavaScript closures compared to instances of classes

Exploring the realm of theoretical programming rather than practical applications, my focus has turned towards closures in JavaScript. In essence, a closure is a function with its own exclusive set of variables that are not accessible to copies of the func ...

The observable did not trigger the next() callback

I'm currently working on incorporating a global loading indicator that can be utilized throughout the entire application. I have created an injectable service with show and hide functions: import { Injectable } from '@angular/core'; import ...

Invoking vscode Extension to retrieve data from webview

One task I'm currently working on involves returning a list from the extension to be displayed in the input box of my webview page. The idea is for a JavaScript event within the webview to trigger the extension, receive the list object, and then rend ...

Values in Local Storage are not located upon first attempt, but after a reload they function properly

import {useEffect} from 'react'; import {useRouter} from 'next/router'; const AuthenticationGuard=props=>{ const {children,fallback} = props; const auth = useAuth(); const router=useRouter(); useEffect(()=>{ if(!r ...

Displaying and hiding a large image using jQuery's mouseover event

I'm currently utilizing this jQuery script to toggle the visibility of an image with a fixed position: $(document).on('mouseover',".multiverseid", function (e) { var mid = $(this).attr("id"); $('#picture').attr('s ...

What You See Is What You Get - A versatile tool for editing both text and

As a developer, I have encountered a common need that StackOverflow addresses. Situation I am in the process of creating a website where users can post code examples and articles using an admin system. These posts may be created by me or registered fron ...

Sending a JSON object back to HTML

In the process of developing a web app, I encountered a need to update the configuration of a specific graph type. My current approach involves utilizing Python3 with Flask and HTML. My objective is to achieve dynamic configuration updates without relying ...

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

Tips for navigating between modal data in ng-repeat with the use of angular ui modals

I am new to Angular JS and I have a question related to populating data using ng-repeat from a local JSON file. When the data is clicked, it should display more detailed information about the selected company. Now, I want to implement the functionality for ...

What is the best way to integrate my PHP regular expression into Node.js code?

I recently encountered an issue when trying to convert a regular expression from PHP to Node.js. The output I'm receiving in Node.js is different from what I expect, and I suspect it has to do with my implementation of PREG_SET_ORDER in Node.js. Here ...

Loading a div using Ajax within a frame

My php page includes a div that is supposed to be populated by an Ajax call. function showcopay() { var apa = document.getElementById("alert_id").value; $("#copay").load('show_copay.php?pid='+apa); } The parent page of the div used to be ...

I am facing an issue with the Options functionality in Materialize, and the remove method does not seem to work when I am using the

Having a little trouble appending options in a materialize select for my project. Can someone take a look at my code snippet below and provide some guidance on what changes I should make? Thanks! $(document).ready(function() { $(".condition").click(fu ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

Popup windows are struggling to close correctly

Having an issue with multiple popups not closing properly when clicking another link. The popups keep stacking up even though the close function has been specified in the code. $(document).ready(function() {//$('a.poplight[href^=#]').click(funct ...

The GLTFLoader in Three.js is struggling to accurately interpret the .glb file

After developing a React app with three.js initialized scene, I encountered an error when trying to load a model with GLTFLoader. The specific error message is as follows: GLTFLoader.js:192 SyntaxError: Unexpected token '<', "<!DOCTYPE ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

Tips for preventing the use of nested functions while working with AJAX?

Consecutively making asynchronous calls can be messy. Is there a cleaner alternative? The issue with the current approach is its lack of clarity: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); ...

Ways to halt the terminal from continuing execution upon an async function's completion

After running my code, I encounter an issue where the terminal continues to run indefinitely, requiring manual intervention to close it. In previous instances, using mongoose.disconnect() effectively stopped this behavior. However, in my current situation, ...

Regular Expression: Removing the trailing newline character from a match

Seeking a regular expression to identify the first date that is not followed by a line starting with the letter 'R' (aiming to obtain the last commit date from git log, omitting only path-changing commits). 2021-12-07T16:39:43+01:00 M test. ...