Getting value from radio button with Javascript - javascript

I am trying to check if the radio button is checked or not, and also I am trying to get the value but I do not know why it does not work. I saw a lot of post, video on internet and also some on this site, but nothing. So helpless I am posting this on the site.
This is my HTML file
function getValue(){
var checkAge = false;
for(var i=0; i<4; i++){
if(document.getElementById("age"+i).checked){
checkAge = true;
}
}
}
function loadFunctions() {
getValue();
}
window.onload = loadFunctions;
<!DOCTYPE html>
<html>
<head>
<title>Tutorial</title>
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<form id="form">
<section id="age_question">
<h2>How old are you?</h2>
<label for="age-one">1-25</label>
<input type="radio" name="ageRange" id="age1" value="0"/>
<label for="age-two">26-40</label>
<input type="radio" name="ageRange" id="age2" value="5" />
<label for="age-three">41-60</label>
<input type="radio" name="ageRange" id="age3" value="8" />
<label for="age-four">60+</label>
<input type="radio" name="ageRange" id="age4" value="10" />
</section>
<section id="bmi">
<h2>What is your BMI?</h2>
<label for="bmi-level"><span>0-25</span></label>
<input type="radio" name="bmi_range" id="" value="0"/>
<label for="bmi-level"><span>26-30</span></label>
<input type="radio" name="bmi_range" id="" value="0" />
<label for="bmi-level"><span>31-35</span></label>
<input type="radio" name="bmi_range" id="" value="9" />
<label for="bmi-level"><span>35+</span></label>
<input type="radio" name="bmi_range" id="" value="10" />
</section>
<section id="family_history">
<h2>Does anybody in your family have Diabetes?</h2>
<label for="history"><span>No</span></label>
<input type="radio" name="f_history" id="history" value="0"/>
<label for="history"><span>Grandparent</span></label>
<input type="radio" name="f_history" id="history" value="7" />
<label for="history"><span>Sibling</span></label>
<input type="radio" name="f_history" id="history" value="15" />
<label for="history"><span>Parent</span></label>
<input type="radio" name="f_history" id="history" value="15" />
</section>
<section id="diet">
<h2>How would you describe your diet?</h2>
<label for="diet"><span>Low sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0"/>
<label for="diet"><span>Normal sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="0" />
<label for="diet"><span>Quite high sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="7" />
<label for="diet"><span>High sugar</span></label>
<input type="radio" name="dietHabits" id="dietHabit" value="10" />
</section>
<button onclick="getValue()">Get You BMI</button>
<p id="message"></p>
</form>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>

The first thing I'll suggest you do is to clear your browser cache, or launch the dev tools using F12 and check "Disable cache" on the "Network" tab.
Edit: Changed the button type, and made checkAge global.
Okay, the button does submit the form, making all changes to the variable lost after reload. To fix that, change the button type to just button, as:
<button type="button" onclick="getValue()">Get You BMI</button>
That way, it won't reload everytime you press the button. Another thing to do is make the checkAge variable global. that way is defined as false by default.
The "age"+i thing you did was starting the iteration with i=0, therefore giving the elementId as age0. This was making the element null.
To fix that, you can change the for-loop to for(var i=1; i<=4; i++) or using the same loop you've defined, but adding i by 1 before using it.
And the code would be like so:
var checkAge = false;
function getValue(){
for(var i=0; i<4; i++){
var index = i + 1
var element = document.getElementById("age"+index)
if(element.checked){
checkAge = true;
alert("The value is"+element.value)
}
}
}
Thanks.

Make the starting index be 1 instead of 0, since your ID selectors start from 1:
function getValue() {
var checkAge = false
for (var i = 1; i <= 4; i++) {
if (document.getElementById('age' + i).checked) {
checkAge = true
}
}
console.log(checkAge)
return checkAge
}
JSFiddle Demo: https://jsfiddle.net/a3fzd2kv/2/

You don't need to check the checked value of each of the radio buttons.
Here is a simpler solution:
var form = document.getElementById('form');
var ageRange = form.ageRange.value;
The value will equal to an empty string ('') when nothing is checked. Therefore, the logic for checkAge could be simplified to:
var checkAge = ageRange !== '';

your for loop is looping through i from 0 - 3, so your document.getElementById("age"+i) will look for id="age0", "age1", "age2, "age3".
Change your 'for' loop to for(var i=1; i<5; i++)

Related

display the value of all selected radio buttons on a form

I have multiple radio buttons generated in a php loop which looks something like this
while(){
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team1'].' " onclick="return disp()""><span>'.$team1.'</span>
<input type="radio" id="picks'.$x.'" name="picks['.$x.']" value="'.$row['team2'].' "onclick="return disp()""><span>'.$team2.'</span>
<input type="radio" name="picks'.$x.'" value="draw" onclick="return disp()">
}
What I want to do
Display all selected radio buttons in a div on the bottom of page
My Code
var elmnts = document.getElementById("makePicksForm").elements
var lngth = document.getElementById("makePicksForm").length;
var div = document.getElementById("dispPicks");
for (var x = 0; x < lngth; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML = elmnts[x].value;
}
}
My Problem
Only the value of first selected radio button is displayed in div, other radio buttons are ignored
My Question
Any idea how I can modify my javascript to display the values of ALL selected radio buttons?
Since you've tagged your question with jQuery, here is a jQuery solution. Run the snippet to see it work:
$(document).ready(function () {
$(':radio').change(function (e) {
//clear the div
$('#dispPicks').html('');
//update the div
$(':radio:checked').each(function (ind, ele) {
$('#dispPicks').append($(ele).val() + '<br/>');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="foo" value="foo1" />
<input type="radio" name="foo" value="foo2" />
<input type="radio" name="foo" value="foo3" />
<br/>
<input type="radio" name="bar" value="bar1" />
<input type="radio" name="bar" value="bar2" />
<input type="radio" name="bar" value="bar3" />
<br/>
<input type="radio" name="wow" value="wow1" />
<input type="radio" name="wow" value="wow2" />
<input type="radio" name="wow" value="wow3" />
<div id="dispPicks"></div>
You're using lngth in your for loop, but that's defined by getting an element by ID which should only be 1 element. Your loop will only run once that way...
Assuming the element with ID makePicksForm contains all your radio buttons, you need to get the length of the elements:
var elmnts = document.getElementById("makePicksForm").elements;
var div = document.getElementById("dispPicks");
for (var x = 0; x < elmnts.length; x++) {
if (elmnts[x].type == "radio" && elmnts[x].checked == true) {
div.innerHTML += elmnts[x].value;
}
}
Also, you need to add the value to the innerHTML property, using +=
as a side note: your PHP loop is creating duplicate ID's, which will result in failures in your javascript code if you need to reference the elements...
Another jQuery-Fiddle
<input type="radio" id="bob" name="boys" value="Bob"><label for="bob">Bob</label><br>
<input type="radio" id="jim" name="boys" value="Jim"><label for="jim">Jim</label><br>
<input type="radio" id="pete" name="boys" value="Pete"><label for="pete">Pete</label><br>
<input type="radio" id="mary" name="girls" value="Mary"><label for="mary">Mary</label><br>
<input type="radio" id="jane" name="girls" value="Jane"><label for="jane">Jane</label><br>
<input type="radio" id="susan" name="girls" value="Susan"><label for="susan">Susan</label>
<h3><span id="boy">?</span> and <span id="girl">?</span></h3>
$("input[name=boys]").click(function () {
$("#boy").text($(this).val());
});
$("input[name=girls]").click(function () {
$("#girl").text($(this).val());
});

textbox.value not working in javascript

The following is a simple javascript code to set a value into a textbox. But, it doesn't seem to work. I am not able to find the flaw. Also, the javascript is working only in IE and not in Chrome/Firefox. How do I get out of this trouble?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function reportValue()
{
var form = document.getElementById("billgen");
var radioArray = form["time"];
var months;
for(var i=0;i<radioArray.length;i++)
{
if(radioArray[i].checked)
{
months = radioArray[i].value;
break;
}
}
if(months == "1")
{
e=31*100;
form["total"].value = e;
//document.getElementById("total").value = e; => not working as well
return true;
}
else{
alert("Are you sure the instructor is " + months + "?\nYou may be underestimating the instructor!");
return false;
}
}
</script>
</head>
<body bgcolor="white">
<fieldset>
<legend>Bill Generation</legend>
<form id="billgen" method="post">
<label><input type="radio" name="time" value="1" checked /> 1 Month </label>
<label><input type="radio" name="time" value="3" /> 3 Month </label>
<label><input type="radio" name="time" value="6" /> 6 Month </label>
<label><input type="radio" name="time" value="12" /> 1 Year </label>
<input type="submit" value="submit" onclick="reportValue();" />
<p>
<input type="text" id="total" name="total" />
</p>
</form>
</fieldset>
</body>
</html>
Clicing on a <input type="submit"/> causes the page to reload, so instead of "submit", either use the <button> element or use an <input type="button"/>.
Here is your code with getElementById( instead of getElementById[: JSFiddle and it works.
Just move your code to the end of your html, just before the </body> and it should work, I think the problem is that you are asigning the form to a variable before the form even exists.

Radio buttons selected go to URL

I am trying to use the value of the selected radio button to go to a specific URL. Currently the Javascript I am using to do so is choosing the first "id" of the inputs and not using the value of what is actually selected.
HTML
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
Javascript
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + document.getElementById('ns_license').value;
}
</script>
You have multiple ID's that are the same, which is bad! getElementById expects one result, and it gets one by taking the first element which has that ID (ignoring your other 2, as it should). Use the class attribute on similar elements.
<input type="radio" name="ns_license" class="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" class="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" class="ns_license" value="1026" />NeuroSolutions Student
And to get the checked element
var checkedElem = document.querySelector(".ns_license:checked");
And if querySelector is out of the question:
var elems = document.getElementsByClassName("ns_license"),
checkedIndex = 0;
for (var i = 0; i < elems.length; i++) {
if (elems[i].checked)
checkedIndex = i;
}
Your current checked element would be at elems[checkedIndex]
to change a a specific attribute of an element, you can use the
setAttribute()
function of javascript. that should make it work.
While querySelector will work for modern browsers it does not work for IE <=7
If you want you can traverse through the radios by name, then check if the value is checked. If it is then return that value. That is the use of the getRadioValue() function:
<form action="https://www.neurodimension.net/solo/products/Cart.aspx" method="POST" id="myForm" onsubmit="changeActionURL();">
<input type="radio" name="ns_license" id="ns_license" value="1025" />NeuroSolutions Pro<br />
<input type="radio" name="ns_license" id="ns_license" value="1024" />NeuroSolutions<br />
<input type="radio" name="ns_license" id="ns_license" value="1026" />NeuroSolutions Student
<input type="submit" />
</form>
<script type="text/javascript">
function changeActionURL() {
var forma = document.getElementById('myForm');
forma.action += "?action=add&actiondata0=" + getRadioValue('ns_license');
}
function getRadioValue(name){
var rads = document.getElementsByName('ns_license');
for(var x=0; x<rads.length;x++){
if(rads[x].checked){
return rads[x].value;
}
}
}
</script>

Print values of selected radio buttons and check-boxes and exclude the submit button

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).
Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).
How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += elem[i].value+"<br>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Add the following test:
if(elem[i].checked)
str += elem[i].value+"<br>";
Also, if you use jQuery, the whole script is even simpler:
function DisplayFormValues(){
$("input:checkbox:checked").add("input:radio:checked")
.each(function(){
$("div#lblValues").append(this.value + "<br>");
});
}

Selecting an html radio button dynamically through javascript does not work in IE

I want to select a radio button from javascript. I am using this simple html file to test the issue. The code below works correctly on firefox and chrome, however it does not work in IE (no version works). I would like to know why the supplied code does not work on IE, and how to select a radio button in IE?
<html>
<head>
<script type="text/javascript">
function chooseOne()
{
var randomChoice = Math.round(Math.random() * 2);
if(randomChoice == 0)
{
document.getElementById("test0").checked = true;
}
else if (randomChoice == 1)
{
document.getElementById("test1").checked = true;
}
else
{
document.getElementById("test2").checked = true;
}
}
</script>
</head>
<body>
<input type="radio" id="test0" name="test" value="a" /> A<br />
<input type="radio" id="test1" name="test" value="b" /> B<br />
<input type="radio" id="test2" name="test" value="c" /> C<br />
<input type="button" name="click" value="CHOOSE" onclick="javascript:chooseOne()" />
</body>
Thanks in Advance,
Spi
First of all, you should give all your radio buttons the same name, otherwise they will act as if they are independent buttons:
<input type="radio" name="test" id="test0" value="a" /> A<br />
<input type="radio" name="test" id="test1" value="b" /> B<br />
<input type="radio" name="test" id="test2" value="c" /> C<br />
I'm guessing this is also the source of your problem. Further, once you do this, you only need to set one radio button's checked to true, that will automatically remove the selection from other buttons.
I'm not certain, but possibly you have to tell IE that your onclick code is in javascript like this:
<input type="button" name="click" value="CHOOSE" onclick="javascript:chooseOne()" />
One problem:
var randomChoice = Math.round(Math.random() * 2);
will always yield to 1

Categories