Home > Web Front-end > JS Tutorial > How to Correctly Retrieve the Value of a Selected Radio Button in JavaScript?

How to Correctly Retrieve the Value of a Selected Radio Button in JavaScript?

Susan Sarandon
Release: 2024-12-15 17:17:11
Original
910 people have browsed it

How to Correctly Retrieve the Value of a Selected Radio Button in JavaScript?

Retrieving the Value of a Selected Radio Button

When trying to obtain the value of a radio button, you may encounter issues resulting in undefined values returned. Understanding the reasons behind this behavior is crucial to finding a solution. Let's examine the code and suggest a solution.

In the provided code:

function findSelection(field) {
  var test = 'document.theForm.' + field;
  var sizes = test;
Copy after login

You are incorrectly trying to access the form element by converting the string to a variable, which is not how DOM elements are accessed in JavaScript. This will result in undefined.

To resolve this, you should use document.querySelector or document.querySelectorAll to accurately select the form inputs.

Here's an improved version:

const radioButtons = document.querySelectorAll('input[name="genderS"]');
for (let i = 0; i < radioButtons.length; i++) {
  if (radioButtons[i].checked) {
    return radioButtons[i].value;
  }
}
Copy after login

Alternatively, you can use the modern approach:

document.querySelector('input[name="genderS"]:checked').value;
Copy after login

This will correctly return the value of the selected radio button without encountering the undefined issue.

The above is the detailed content of How to Correctly Retrieve the Value of a Selected Radio Button in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template