I am creating a survey with a html form with radio buttons.
The user answers 5 questions, and hits submit button that calls a javascript, where I want a loop to get the value from each radio button, and put it all together into one variable.
My problem is, that I cant figure out the correct way to use "i" in the variable called currentVal.
The result I am looking for, should be something like a variable with: "val1, val5, val3, val1, val4"
Totally new at this, so if you can keep the answer noobfriendly ;)
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#check').click(function()
{
for (var i=0; i < 5; i++)
{
var currentQuestion = i;
var currentVal = $("input:radio[name="+ i +"]:checked").val();
}
document.write(currentVal);
});
})
</script>
</head>
<body>
<form name="form" method="post" action="">
Question 1<br/>
<input type="radio" name="1" value="val1"/> Ans1
<input type="radio" name="1" value="val2"/> Ans2
<input type="radio" name="1" value="val3"/> Ans3
<br/><br/>
Question 2<br/>
<input type="radio" name="2" value="val1"/> Ans1
<input type="radio" name="2" value="val2"/> Ans2
<input type="radio" name="2" value="val3"/> Ans3
<br/><br/>
Question 3<br/>
<input type="radio" name="3" value="val1"/> Ans1
<input type="radio" name="3" value="val2"/> Ans2
<input type="radio" name="3" value="val3"/> Ans3
<br/><br/>
Question 4<br/>
<input type="radio" name="4" value="val1"/> Ans1
<input type="radio" name="4" value="val2"/> Ans2
<input type="radio" name="4" value="val3"/> Ans3
<br/><br/>
Question 5<br/>
<input type="radio" name="5" value="val1"/> Ans1
<input type="radio" name="5" value="val2"/> Ans2
<input type="radio" name="5" value="val3"/> Ans3
<input type="button" value="Test" id="check" />
</form>
</html>
currentValin your for-loop but then try to use it outside of your for-loop.document.write()after the page has loaded. @David - Declaring the variable in the loop is messy, but it will be accessible anywhere in the containing function because JavaScript doesn't have block scope...