Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Radio button value retrieval

Status
Not open for further replies.

kondakindi

IS-IT--Management
Apr 18, 2005
31
US
Hi,

I have a couple of radio buttons in my form and when the form is submitted i need to check which radio button is checked. I am not able to get the value of the radio button. even after checking the radio button it is showing a msg not checked.

here is my code.

function validate(f)
{
var empty = false;
if (f.Datetype.checked == true)

alert(f.Datetype.value);
else
alert(" not checked");
}
</script>
<body>
<form name="form1" method="post" action="">
<p><input type="radio" name="Datetype" value="singledate" >Single Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="radio" name="Datetype" value="betweendate">Between Dates
<br>
<p><input type="submit" value="Submit" name="B1" onclick="return validate(this.form)" ><input type="reset" value="Reset" name="B2"></p>
</form>



</BODY>
</HTML>

Thanks in advance
 
It is because Datetype radiobutton form an array/collection. Try this to see what happens.
[tt]
function validate(f)
{
var empty = false;
for (var i=0;i<f.Datetype.length;i++) {
if (f.Datetype.checked == true) {
alert(f.Datetype.value);
//do other thing
} else {
alert("Button " + i + " not checked");
//do other thing
}
}
}
[/tt]
- tsuji
 
If there is only one radio button, then you can refer to it the way you did. If there is more than one, you need to refer to it as a collection. Therefore, I recommend using the getElementsByName() method which will always return a collection. That way you don't have to worry about how many there are. Then loop through like tsuji does:
Code:
function validate(f)
{
    var empty = false;
    var Datetypes = document.getElementsByName("Datetype");
    for (var i=0;i<Datetypes.length;i++) {
        if (Datetypes[i].checked == true) {
            alert(Datetypes[i].value);
            //do other thing
        } else {
            alert("Button " + i + " not checked");
            //do other thing
        }
    }
}

Adam

There are only 10 types of people in the world: Those who understand binary, and those who don't
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top