October 16th, 2013, 08:23 PM
-
Radio button length and checked does not work
Hi I have simple html file with Javascript.
The html has a radio button DogCat.
My JS script is to display the selected value.
I entered some value into the inut box to trigger the JS function.
I encountered two problems:
1) I cannot display the length of the radio button because I got the following alert:
length of radi button is = undefined
2) I don't get any output from the 'alert' statement inside the loop to display the selected value. It is as if nothing was selected.
Can someone help?
Here is my code:
<html>
<head>
<script language="javascript">
function checkDogCat()
{
var whichField = '';
alert("entering checkDogCat() ");
whichField = document.getElementById('DogCat');
alert("length of radi button is = " + whichField.length);
for (var j = 0; j < 2; j++) {
if (whichField[j].checked) {
alert(whichField[j].value);
break;
}
}
}
</script>
</head>
<body>
<form name="CatDogform">
<INPUT TYPE="radio" id = "DogCat" NAME= "DogCat" VALUE="Dog" CHECKED>Dog<BR>
<INPUT TYPE="radio" id = "DogCat" NAME= "DogCat" VALUE="Cat" >Cat<BR>
<input type="text" id="Dog1" maxlength=5 onkeyup="checkDogCat();">
<input type="text" id="Cat1" maxlength=2 onkeyup="checkDogCat()">
</form>
</body>
</html>
October 19th, 2013, 01:38 PM
-
Is this what you were wanting to do (I wasn't 100% sure, so I took at stab at it)?
Code:
<html>
<head>
<script type="text/javascript">
function checkDogCat()
{
var whichField = document.getElementsByTagName('input');
var radios = 0;
for(i=0;i<whichField.length-1;i++){
if(whichField[i].getAttribute("type") == "radio"){
radios++;
}
}
alert("There are " + radios + " radio buttons.");
for (var j = 0; j < whichField.length-1; j++) {
if (whichField[j].checked) {
alert(whichField[j].value);
}
}
}
</script>
</head>
<body>
<form name="CatDogform">
<INPUT TYPE="radio" NAME="DogCat" VALUE="Dog" CHECKED>Dog<BR>
<INPUT TYPE="radio" NAME="DogCat" VALUE="Cat" >Cat<BR>
<input type="text" id="Dog1" maxlength=5 onkeyup="checkDogCat();">
<input type="text" id="Cat1" maxlength=2 onkeyup="checkDogCat()">
</form>
</body>
</html>