How to get switch value with javascript

I need to get the switch value using javascript

I have a radio group called selection

<input type="radio" name="selection" id="selection" value="allClients" checked="checked" />All Clients<br /> <input type="radio" name="selection" id="selection1" value="dateRange" />Date Range between 

I am passing the value to another page using javascript

 onclick="do_action1('liveClickCampaigns','contract_type='+document.getElementById('contract_type').value+'&beginDate='+document.getElementById('beginDate').value+'&endDate='+document.getElementById('endDate').value+'&selection1='+document.getElementById('selection1').value+'&selection='+document.getElementById('selection').value,'content');" type="button"> 

Value of document.getElementById ('selection'). should get the value, but it continues to give me the value of the first switch, even if the second is selected. Radio group is not in shape

+2
javascript html
source share
2 answers

Using:

 function getRadioValue(name) { var group = document.getElementsByName(name); for (var i=0;i<group.length;i++) { if (group[i].checked) { return group[i].value; } } return ''; } 

Application:

 var selectedValue = getRadioValue('selection'); 

Demo:

http://www.jsfiddle.net/tqQWT/

+7
source share

Although the Matt solution works fine and solves your immediate problem, I also recommend that you start learning about the JavaScript library, such as JQuery, if you will frequently query the DOM.

With jQuery, your solution is single-line:

 var selectedValue = $("input[name=selection]:checked").val(); 
+3
source share

All Articles