vaibhav shah
vaibhav shah

Reputation: 5069

not getting radio button value in javascript

In my application I am trying to get value of radio button but some how not able to get it.

my html is

<div style="border-bottom: 5px Solid #800080;">
    <input type="radio" value="0 " name="routeSelect" checked="checked">Route 1</div>
<br>
<div style="border-bottom: 5px Solid #000080;">
    <input type="radio" value="1 " name="routeSelect">Route 2</div>
<br>
<input type="button" onclick="alert(getRadioValue());" value="Which?" />

my js is

function getRadioValue() {

    var group = document.getElementsByName("routeSelect");

    for (var i = 0; i < group.length; i++) {
        if (group[i].checked) {
            return group[i].value;
        }
    }

    return '';
}

Here Is link : http://jsfiddle.net/aX89G/

can any one tell me what is wrong I am doing

Upvotes: 0

Views: 118

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

Your code is fine but the getRadioValue function isn't found, it's currently wrapped in a function which is called on load, you must choose No wrap - in <head> in the menu at the left of jsfiddle's window.

This is equivalent to putting the code in a script element in the head of your page.

Demonstration

Alternatively, you could separate your javascript from your HTML this way :

<input id=butt type="button" value="Which?" />

<script>
    document.getElementById('butt').onclick=function(){
       alert(getRadioValue());
    });
</script>

This is usually considered cleaner and easier to maintain.

Upvotes: 4

Related Questions