iTechMedium Uncategorized how to fetch value of selected radio button in javascript

how to fetch value of selected radio button in javascript

By the Loop through those elements to check which is checked. You can try document.getElementsByName(<button_name>) or document.getElementsByTagName("input") to get an array of input elements. 



You can see this example of how to fetch the value of the checked button from a set of radio buttons with the name "selected".

You can do similar for check box.


<html>
<head>
<script type="text/javascript">
function get_radio_value() {
var inputs = document.getElementsByName("selected");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
return inputs[i].value;
}
}
}

function onSubmit() {
var id = get_radio_value();
alert
("selected input is: " + id);
}
</script>
</head>
<body>
<form onsubmit="onSubmit();">
<input name="selected" value="1" type="radio"/>1<br/>
<input name="selected" value="2" type="radio"/>2<br/>
<input name="selected" value="3" type="radio"/>3<br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *