Skip to content
the poor coder

how to know which radio button is selected javascript

Poor Man
Published
Reading time
1 min read

The easiest way to know which radio button is selected in JavaScript is to use the `.checked` property. This property is a boolean value that is true when the radio button is checked and false when the radio button is not checked. Here is an example of how to check if a radio button is selected: ``` Option 1 Option 2  let selected = document.querySelector('input[name="example"]:checked').value; console.log(selected); ``` In the example above, we use the `document.querySelector()` method to select the radio button with the name attribute of "example" that has been checked. Then we use the `.value` property to get the value of the selected radio button. You can also use the `.checked` property to check if a radio button is selected without having to select the radio button. Here is an example: ``` Option 1 Option 2  let option1 = document.querySelector('input[name="example"][value="1"]').checked; let option2 = document.querySelector('input[name="example"][value="2"]').checked; console.log(option1); console.log(option2); ``` In the example above, we use the `document.querySelector()` method to select the radio button with the name attribute of "example" and the value attribute of "1" or "2". Then we use the `.checked` property to determine if the radio button is selected or not. You can also use the `.addEventListener()` method to detect when a radio button is selected. Here is an example: ``` Option 1 Option 2  let radios = document.querySelectorAll('input[name="example"]'); radios.forEach((radio) => { radio.addEventListener('change', (e) => { let selected = e.target.value; console.log(selected); }); }); ``` In the example above, we use the `document.querySelectorAll()` method to select all the radio buttons with the name attribute of "example". Then we use the `.addEventListener()` method to detect when a radio button is selected and get the value of the selected radio button. Hopefully this helps you understand how to determine which radio button is selected in JavaScript.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC