Access to switch value through form identifier

I am working on a site with several forms of radio buttons, one of which looks like this:

<form id = "configuration"> <ul> <li><input type="radio" name="configuration" id="0" value="0"/> GT Manual</li> <li><input type="radio" name="configuration" id="1" value="1"/> GT Automatic</li> </ul> </form> 

THERE is a way (javascript) so that I can directly access the values ​​of the switches, e.g.

 var value = document.getElementById("configuration").configuration.value; 

(here, the first “configuration” is the form identifier, and the second “configuration” is the name, not the loop through each element in the form, to check which button is selected?

Thanks!

+4
source share
4 answers

Get it like this:

 var radios = document.getElementsByName('configuration'); for (i = 0; i < radios.length; i++) { if (radios[i].type == 'radio' && radios[i].checked) { alert(radios[i].value); } } 
+2
source

No. You need to loop into a group of radio to find out which one is selected. .configuration is a standard NodeList, not a "subclass" with additional functions for processing groups of radio stations.

+1
source

Since the Radio buttons are part of a group that has the same name, they are identified by a separate identifier. The answer provided by KyleK is absolutely correct. However, there is another way to do this http://jsfiddle.net/9W76C/

 if (document.getElementById('0').checked) { alert("GT Manual"); } 

I also suggest you use jquery ...

-1
source

If you use jQuery, you can do $('#configuration input:checkbox').val(); to find out which one is selected

-1
source

Source: https://habr.com/ru/post/1491371/


All Articles