Javascript получить выбранный radio

Как получить значение radio js

Иногда нам может потребоваться получить значение выбранного переключателя в нашем веб-приложении. Рассмотрим пример.

 id="fruits">  type="radio" name="fruit" value="apple">Apple  type="radio" name="fruit" value="orange">Orange  type="radio" name="fruit" value="grape" checked="checked">Grape  onclick="viewRadio();">Показать значение 

Напишем функционал, который выберет все радио-кнопки на странице и выведет значение только той, у которой атрибут есть checked.

const viewRadio = () =>  const fruits = document.querySelectorAll('input[name="fruit"]'); for (const f of fruits)  if (f.checked)  alert(f.value) > > > 

Источник

How to Get the Selected Radio Button Value in JavaScript

A group of radio buttons in HTML allows the user to select only one option from multiple options. In this tutorial, we will learn how to create a group of HTML radio buttons and get which one is selected using JavaScript.

Creating a Group of Radio Buttons in HTML

In HTML radio buttons are grouped by a unique name attribute. If the radio input does not have the same name attribute it will be independently selectable. In the example below only one of the following radio buttons can be selected because they all have the name attribute of day :

label for="monday">Mondaylabel> input type="radio" name="day" id="monday"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday"> 

How to Get the Selected Radio Button

Since we know a group of radio buttons is defined by a name attribute we can get them using the JavaScript document.getElementsByName() method, passing the name attribute inside the () (parenthesis) of the method.

This will return an object of elements. All we have to do is iterate through the object using a for of loop and check which one is selected using the JavaScript .checked method.

label for="monday">Mondaylabel> input type="radio" name="day" id="monday" value="1"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday" value="2" checked="checked"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday" value="3"> 
var days = document.getElementsByName('day'); for (let i of days)  if (i.checked)  console.log(i.id); > > 

The above example gets the ID of the radio button if it is checked. To get the value of a radio button use the value JavaScript property:

var days = document.getElementsByName('day'); for (let i of days)  if (i.checked)  console.log(i.value); > > 

Get the Selected Radio Button Without Iterating

It is possible to get the selected radio button without iterating by using the JavaScript document.querySelector() method.

label for="monday">Mondaylabel> input type="radio" name="day" id="monday" value="1"> label for="tuesday">Tuesdaylabel> input type="radio" name="day" id="tuesday" value="2" checked="checked"> label for="wednesday">Wednesdaylabel> input type="radio" name="day" id="wednesday" value="3"> 
var selected = document.querySelector('input[name="day"]:checked').id; console.log(selected); 

The above example gets the ID of the radio button that is checked. Alternatively, you could get its value like this:

var selected = document.querySelector('input[name="day"]:checked').value; console.log(selected); 

Conclusion

You now know two different ways of getting the selected radio button using JavaScript.

Источник

How to Get Value of Selected Radio Button Using JavaScript?

One of the most important HTML components when attempting to design a form is the radio button. The user can only select one choice from the alternatives shown to him by the radio buttons.

Typically, we just utilize the element’s value attribute in JavaScript to retrieve an element’s value from an HTML webpage. But with radio buttons, we can’t do that. The reason is that getting the values of individual radio buttons is a bad idea.

Let’s get started with the article to learn how to get the value of a selected radio button. For this, we are going to use the checked attribute.

Using checked attribute

The checked attribute is a Boolean attribute. When present, it indicates that an element should be pre-selected (checked) when the page loads. The checked attribute can be used with both checkbox and radio input types. With JavaScript, the checked attribute can also be modified after the page has loaded.

Syntax

Following is the syntax for checked attribute −

Let’s look at some examples to get a better idea of how to get the value of a selected radio button

Example

In the following example, we are running the script for getting the value of the selected radio button.

    

Choose The Course

When the script gets executed, it will generate an output consisting of text along with radio buttons and a click button. When the user selects the radio button and clicks, a pop-up window displays the value you have chosen.

Example

Considering the following example, where we are running the script to get the value of the selected radio button.

    

Choose Value And Click Submit Button

Choose: Login In Sign Up

On running the above script, the output window will pop up, displaying the text along with a radio button and a submit button. When the user selects the radio button and clicks the submit button, the event gets triggered and displays the chosen value.

Using the querySelector() function

The document’s first element that matches the given selector or set of selectors is returned by the querySelector() function. Null is returned if no matches were discovered.

Syntax

Following is the syntax for querySelector()

Example

Execute the below code and observe how we are getting the value of the selected radio button.

    

Choose The Gender:

document.getElementById('click').onclick = function()

When the script is run, it will generate an output consisting of text along with a radio button and a submit button. When the user chooses the values and clicks the button, a pop-up window displaying the chosen.

Источник

Как получить значение (value) выбранной радио кнопки по атрибуту name с помощью JS?

По итогу выводится только самое первое значение, а другие игнорируются. В консоли никаких ошибок не выдает.

Simkav

Потому что у вас стоит обработчик только на 1 инпут
querySelector выдаст вам первое найденое совпадение, вам нужно юзать querySelectorAll

var text = ['BASIC', 'STANDART', 'ADVANCED']; const inputs = document.querySelectorAll('input[name="rate"]'); inputs.forEach((item) => < item.addEventListener('change', function () < const = this; if (value == 1) < document.getElementById('result').innerHTML = text[0]; >else if (value == 2) < document.getElementById('result').innerHTML = text[1]; >else if (value == 3) < document.getElementById('result').innerHTML = text[2]; >>); >);

Подскажите еще пожалуйста: я раньше использовал селектор вместо радиокнопок для калькулятора roi, как мне поменять данный скрипт:

 

Simkav

Simkav, выше я написал код калькулятора расчета окупаемости.
Пользователь выбирает одну из опций, раньше они были представлены в селекторе, сейчас хочу представить через радио-кнопки, далее вводит сумму, и калькулятор выдает в зависимости от введенной суммы и выбранной опции различные показатели: roi, aRR, mRR.
Я не могу грамотно и корректно передать value радио-кнопок, с которыми потом работает калькулятор.
Раньше это было просто, тк у селектора всего один id на все его опции:

 
const projectionScenarioInput = document.querySelector('#option') // тут обработчик клика по селектору projectionScenarioInput.addEventListener('change', calculateReturns) // тут формула расчета function calculateReturns (e) < const totalCustomers = parseInt(totalCustomerBaseInput.value) const projectionPercent = parseFloat(projectionScenarioInput.value) const mRR = totalCustomers / 100 * projectionPercent *30 const roi = mRR / 30 if (projectionPercent == 1.7) < aRRContainer.innerHTML ="$" + (totalCustomers + (roi * 15)).toFixed(1) >// тут сами расчеты и потом вывод значений
const projectionScenarioInput = document.querySelector('input[name="option"]') projectionScenarioInput.addEventListener('change', calculateReturns)
const projectionScenarioInput = document.querySelectorAll('input[name="option"]') projectionScenarioInput.addEventListener('change', calculateReturns)
projectionScenarioInput.addEventListener('change', calculateReturns)

Источник

Читайте также:  Math signum в java
Оцените статью