Reputation: 1109
I have a radio button on my HTML page:
<form name="myForm" onsubmit="calc_risk(); return false;" method="post">
<input type="radio" name="q1" value="1"> Yes
<input type="radio" name="q1" value="0"> No
<input type="submit" value="Submit">
</form>
Inside my javascript function I can access the value via:
function calc_risk () {
var a = document.forms["myForm"]["q1"].value;
}
In firefox that variable contains 1 or 0 as expected (depending on which radio button I've selected). In IE11 the value is undefined. Why is the radio button not working in IE11?
EDIT
I'm using jquery now to access the value:
var radioValue = $("input[name='q1']:checked").val();
Works in both browsers. Make sure that jquery is included in your header section by adding:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Upvotes: 0
Views: 3786
Reputation: 3844
Here is my solution and tested in IE 11 and Chrome browser.
<html>
<body>
<form name="myForm" onsubmit="calc_risk(this); return false;" method="post">
<input type="radio" name="q1" value="1"> Yes
<input type="radio" name="q1" value="0"> No
<input type="submit" value="Submit">
</form>
<script language="javascript">
function calc_risk (theForm)
{
var q1Values = theForm.q1;
for (i=0 ;i<q1Values.length;i++)
{
if(q1Values[i].checked)
{
alert(q1Values[i].value);
}
}
}
</script>
</body>
</html>
Upvotes: -1
Reputation: 943751
The ability to access a value
property on an HTMLFormControlsCollection and get the value of the first checked radio button inside it is a relatively new feature in the web api specifications.
Internet Explorer (being an old browser that isn't getting any new development work beyond security patches) doesn't support it.
You can loop over the collection and test for the first checked element instead.
var a = get_first_checked_value(document.forms["myForm"]["q1"]);
function get_first_checked_value(form_controls) {
for (var i = 0; i < form_controls.length; i++) {
if (form_controls[i].checked) {
return form_controls[i].value;
}
}
}
Upvotes: 2