简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM