In the form we need to like to have a scenario where we need to write a java script code for checking whether we need the radio has been selected or not?
The below example tells you to how to write a JavaScript for checking the radio button is checked or not.
<html>
<head>
<script language="javascript">
function GetSelectedItem() {
chosen = ""
len = document.f1.r1.length
for (i = 0; i <len; i++) {
if (document.f1.r1[i].checked) {
chosen = document.f1.r1[i].value
}
}
if (chosen == "") {
alert("No Location Chosen");
return false;
}
else {
alert(chosen)
return true;
}
}
</script>
</head>
<body>
<form name="f1" action="" onsubmit="return GetSelectedItem();">
<Input type ="radio" Name ="r1" Value = "NE">North East
<Input type = "radio" Name = "r1" Value = "NW">North West
<Input type = "radio" Name = "r1" Value = "SE">South East
<Input type = "radio" Name = "r1" Value = "SW">South West
<Input type = "radio" Name = "r1" Value = "midlands">Midlands
<input type="submit" value="submit">
</form>
</body>
</html>
Here we have a javascript method GetSelectedItem() which will be invoked when a submit button is pressed. document.f1.r1.length will tells the length of the radio buttons present. The for loop will check all the radio buttons and find if even a single radio button is checked or not.
This is awesome! Thanks for your help!!!! What is the need to store the values in CHOSEN? Wondering..thanks again
ReplyDelete