I am new to javaScript and am confused on how I should get the total from the checked radio boxes. Also I am trying to add a submit button for the user, so that the total will only be revealed after they click submit. I feel as though I may not be parsing the values properly?
Appreciate the help
Thanks!
<html>
<head>
<script>
function calculateTotal() {
var score = 0;
q1 = new Array(1,2,3,4,5);
q2 = new Array(1,2,3,4,5);
q3 = new Array(1,2,3,4,5);
q4 = new Array(1,2,3,4,5);
q5 = new Array(1,2,3,4,5);
for (var i = 0; i < q1.length; i++ ) {
if(q1[i].checked){
score += parseFloat(q1[i].value);
}
for(var c = 0; c < q2.length; c++){
if(q2[i].checked){
score += parseFloat(q2[i].value);
}
for(var c = 0; c < q3.length; c++){
if(q3[i].checked){
score += parseFloat(q3[i].value);
}
for(var c = 0; c < q4.length; c++){
if(q4[i].checked){
score += parseFloat(q4[i].value);
}
for(var c = 0; c < q5.length; c++){
if(q5[i].checked){
score += parseFloat(q5[i].value);
}
}
}
}
}
}
}
</script>
</head>
<p class="question">1. Rate your family life?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="e" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="e" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="e" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="e" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to
energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="a" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="b" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="c" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="d" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="d" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<script>
alert("Your overall score is " + calculateTotal());
</script>
What you want to do is to get your checkboxes as arrays, not create some unrelated arrays yourself. That can be done using document.getElementsByName("q1");
function calculateTotal() {
var score = 0;
q1 = document.getElementsByName("q1");
q2 = document.getElementsByName("q2");
q3 = document.getElementsByName("q3");
q4 = document.getElementsByName("q4");
q5 = document.getElementsByName("q5");
for (var i = 0; i < q1.length; i++ ) {
if(q1[i].checked){
score += parseFloat(q1[i].value);
}
for(var c = 0; c < q2.length; c++){
if(q2[i].checked){
score += parseFloat(q2[i].value);
}
for(var c = 0; c < q3.length; c++){
if(q3[i].checked){
score += parseFloat(q3[i].value);
}
for(var c = 0; c < q4.length; c++){
if(q4[i].checked){
score += parseFloat(q4[i].value);
}
for(var c = 0; c < q5.length; c++){
if(q5[i].checked){
score += parseFloat(q5[i].value);
}
}
}
}
}
}
}
EDIT: Oh, and for the button to calculate the checked values by the user, you can do really easy something like:
<div onClick="calculateTotal();"> Calculate total </div>
You add a button, attach an event handler to that button, and calculate the total
document.getElementById('total').addEventListener('click', calculateTotal);
function calculateTotal() {
var els = document.querySelectorAll('input[type=radio][name^=q]:checked');
var val = [].map.call(els, function(el) {
return "abcde".split('').indexOf(el.value) + 1;
});
var tot = val.reduce(function(a, b) {
return a + b
});
alert(tot);
}
<p class="question">1. Rate your family life?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="e" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="a" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="b" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="c" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="d" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="e" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="a" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="b" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="c" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="d" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="e" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="a" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="b" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="c" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="d" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="e" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="a" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="b" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="c" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="d" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="d" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<button id="total">Total</button>
Here is a working example. You will want to change the value="" to the value you want to add. the document.getElementsByNames("").value will get this value. Also your for loops are all nested which you don't want to do.
You can add a button with an onclick method to call the method you want. since all the values have the same length you can get away with just one for loop. You also probably want to add a tag for your html body.
function calculateTotal() {
var score = 0;
q1 = document.getElementsByName("q1");
q2 = document.getElementsByName("q2");
q3 = document.getElementsByName("q3");
q4 = document.getElementsByName("q4");
q5 = document.getElementsByName("q5");
for (var i = 0; i < q1.length; i++) {
if (q1[i].checked) {
score += parseFloat(q1[i].value);
}
if (q2[i].checked) {
score += parseFloat(q2[i].value);
}
if (q3[i].checked) {
score += parseFloat(q3[i].value);
}
if (q4[i].checked) {
score += parseFloat(q4[i].value);
}
if (q5[i].checked) {
score += parseFloat(q5[i].value);
}
}
return score;
}
Here is what one of the radio buttons should look like.
1. Rate your family life?
<ul class="answers">
<input type="radio" name="q1" value="1" id="q1a"><label for="q1a">1</label>
<br/>
<input type="radio" name="q1" value="2" id="q1b"><label for="q1b">2</label>
<br/>
<input type="radio" name="q1" value="3" id="q1c"><label for="q1c">3</label>
<br/>
<input type="radio" name="q1" value="4" id="q1d"><label for="q1d">4</label>
<br/>
<input type="radio" name="q1" value="5" id="q1e"><label for="q1e">5</label>
<br/>
</ul>
<p class="question">2. Rate your romantic life?</p>
<ul class="answers">
<input type="radio" name="q2" value="1" id="q2a"><label for="q2a">1</label>
<br/>
<input type="radio" name="q2" value="2" id="q2b"><label for="q2b">2</label>
<br/>
<input type="radio" name="q2" value="3" id="q2c"><label for="q2c">3</label>
<br/>
<input type="radio" name="q2" value="4" id="q2d"><label for="q2d">4</label>
<br/>
<input type="radio" name="q2" value="5" id="q2e"><label for="q2e">5</label>
<br/>
</ul>
<p class="question">3. Rate your social life?</p>
<ul class="answers">
<input type="radio" name="q3" value="1" id="q3a"><label for="q3a">1</label>
<br/>
<input type="radio" name="q3" value="2" id="q3b"><label for="q3b">2</label>
<br/>
<input type="radio" name="q3" value="3" id="q3c"><label for="q3c">3</label>
<br/>
<input type="radio" name="q3" value="4" id="q3d"><label for="q3d">4</label>
<br/>
<input type="radio" name="q3" value="5" id="q3e"><label for="q3e">5</label>
<br/>
</ul>
<p class="question">4. Rate your career/academic life?</p>
<ul class="answers">
<input type="radio" name="q4" value="1" id="q4a"><label for="q4a">1</label>
<br/>
<input type="radio" name="q4" value="2" id="q4b"><label for="q4b">2</label>
<br/>
<input type="radio" name="q4" value="3" id="q4c"><label for="q4c">3</label>
<br/>
<input type="radio" name="q4" value="4" id="q4d"><label for="q4d">4</label>
<br/>
<input type="radio" name="q4" value="5" id="q4e"><label for="q4e">5</label>
<br/>
</ul>
<p class="question">5. Rate how you physically feel (e.g. lethargic 1 to energetic 5)?</p>
<ul class="answers">
<input type="radio" name="q5" value="1" id="q5a"><label for="q5a">1</label>
<br/>
<input type="radio" name="q5" value="2" id="q5b"><label for="q5b">2</label>
<br/>
<input type="radio" name="q5" value="3" id="q5c"><label for="q5c">3</label>
<br/>
<input type="radio" name="q5" value="4" id="q5d"><label for="q5d">4</label>
<br/>
<input type="radio" name="q5" value="5" id="q5e"><label for="q5e">5</label>
<br/>
</ul>
<button type="submit" onclick="alert(calculateTotal())">Submit</button>
The main reason your provided code didn't work was because you forgot to return the calculated score from your function:
function calculateScore() {
// your code...
return score;
}
You also need to make sure each of your loops is closed, with a curly brace, before starting the next one.
However, the most readable way to get the value of a group of radio boxes is to use a form element like so:
function calculateScore() {
var formElement = document.getElementById("the-form"),
score = 0;
score += parseInt(formElement.q1.value);
score += parseInt(formElement.q2.value);
return score;
}
function displayScore() {
document.getElementById("the-score").innerText = calculateScore();
}
<form id="the-form">
<input type="radio" name="q1" value=1 id="q1-a1"><label for="q1-a1">1</label>
<input type="radio" name="q1" value=2 id="q1-a2"><label for="q1-a2">2</label>
<input type="radio" name="q1" value=3 id="q1-a3"><label for="q1-a3">3</label>
<input type="radio" name="q1" value=4 id="q1-a4"><label for="q1-a4">4</label>
<input type="radio" name="q1" value=5 id="q1-a5"><label for="q1-a5">5</label>
<br>
<br>
<input type="radio" name="q2" value=1 id="q2-a1"><label for="q2-a1">1</label>
<input type="radio" name="q2" value=2 id="q2-a2"><label for="q2-a2">2</label>
<input type="radio" name="q2" value=3 id="q2-a3"><label for="q2-a3">3</label>
<input type="radio" name="q2" value=4 id="q2-a4"><label for="q2-a4">4</label>
<input type="radio" name="q2" value=5 id="q2-a5"><label for="q2-a5">5</label>
</form>
<button onclick="displayScore()">Calculate Score</button>
<br>
<output id="the-score"></output>
The form element contains properties named after the name tags of each of the inputs within the form and their values can be accessed with the value property.
By changing the values from a..e to 1..5 the code can be simpler.
Related
I'm a student and I'm going to make a page about the exam.
I'd like to divide several checkboxes so they don't overlap and total sum.
How can I have "q1" and "q2" operate separately?
Only one is checked per question, and whether two are sum together.
<script type="text/javascript">
var sum=0;
function calc(cBox) {
var sumtext = document.getElementById("sumtext");
if(cBox.checked)
sum += parseInt(cBox.value);
else
sum -= parseInt(cBox.value);
sumtext.value = sum;
}
function checkOnly(chk){
var obj = document.getElementsByName("q1");
for(var i=0; i<obj.length; i++){
if(obj[i] != chk){
obj[i].checked = false;
}
}
}
</script>
No.1 Question<br>
<br>
<input type="checkbox" name="q1" value="1"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer1<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer4
</p>
No.2 Question<br>
<br>
<input type="checkbox" name="q2" value="1"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer1<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this);calc(this)" class="sum" >Answer4
</p>
<input type="text" id="sumtext" value="0" >
Update your checkOnly function to add name as arg:
function checkOnly(chk, name){
var obj = document.getElementsByName(name);
for(var i=0; i<obj.length; i++){
if(obj[i] != chk){
obj[i].checked = false;
}
}
}
In the HTML update the method, pass name as second arg:
No.1 Question<br>
<br>
<input type="checkbox" name="q1" value="1"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer1<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q1" value="0"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer4
</p>
No.2 Question<br>
<br>
<input type="checkbox" name="q2" value="1"
onclick="javascript:checkOnly(this, 'q2');calc(this, 'q2')" class="sum" >Answer1<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q2" value="0"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer4
</p>
<input type="text" id="sumtext" value="0" >
var sum=0;
function calc(cBox) {
var sumtext = document.getElementById("sumtext");
if(cBox.checked)
sum += parseInt(cBox.value);
else
sum -= parseInt(cBox.value);
sumtext.value = sum;
}
function checkOnly(chk, name){
var obj = document.getElementsByName(name);
for(var i=0; i<obj.length; i++){
if(obj[i] != chk){
obj[i].checked = false;
}
}
}
No.1 Question<br>
<br>
<input type="checkbox" name="q1" value="1"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer1<br>
<input type="checkbox" name="q1" value="2"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q1" value="3"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q1" value="4"
onclick="javascript:checkOnly(this, 'q1');calc(this)" class="sum" >Answer4
</p>
No.2 Question<br>
<br>
<input type="checkbox" name="q2" value="1"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer1<br>
<input type="checkbox" name="q2" value="2"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer2<br>
<input type="checkbox" name="q2" value="3"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer3<br>
<input type="checkbox" name="q2" value="4"
onclick="javascript:checkOnly(this, 'q2');calc(this)" class="sum" >Answer4
</p>
<input type="text" id="sumtext" value="0" >
On submitting a button I want to get the values of multiple checkboxes where each checkbox have radio buttons. I expect the output will be like if I check
checkbox One and select its corresponding radio button L, checkbox Two and select its corresponding radio button M, checkbox Three and select its corresponding radio button C and it is not mandatory to check all the checkboxes, one may leave some checkbox empty. I want to get the selected item and its corresponding values only.
var allCheckedItem = [];
$.each(jQuery("input[name='teeth']:checked"),
function(){ allCheckedItem.push($(this).val());
});
for (var i = 0; i < allCheckedItem.length; i++)
{
var eachItem = allCheckedItem[i];
console.log(eachItem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<ul>
<li>
<input name='teeth' type="checkbox" id="cb1" value="One" />One
<span class="teethproblem1">
<input name='a' type="radio" id="rb1" value="M" />M
<input name='a' type="radio" id="rb2" value="L" />L
<input name='a' type="radio" id="rb3" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb2" value="Two"/>Two
<span class="teethproblem2">
<input name='b' type="radio" id="rb4" value="M" />M
<input name='b' type="radio" id="rb5" value="L" />L
<input name='b' type="radio" id="rb6" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb3" value="Three"/>Three
<span class="teethproblem3">
<input name='c' type="radio" id="rb7" value="M" />M
<input name='c' type="radio" id="rb8" value="L" />L
<input name='c' type="radio" id="rb9" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb4" value="Four"/>Four
<span class="teethproblem4">
<input name='d' type="radio" id="rb10" value="M" />M
<input name='d' type="radio" id="rb11" value="L" />L
<input name='d' type="radio" id="rb12" value="C" />C
</span>
</li>
<li><input type="submit" name="submit" value="SAVE"></li>
</ul>
</form>
I expect the output should be: One -> M , Two -> C , Three -> L
Here is another variation on the theme:
const getvals=()=>{var coll={};
$(':radio:checked')
.each((i,rb)=>
$(rb).closest('li')
.find(':checkbox:checked')
.each((j,cb)=>coll[cb.value]=rb.value)
)
console.log(coll);
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<ul>
<li>
<input name='teeth' type="checkbox" id="cb1" value="One" />One
<span class="teethproblem1">
<input name='a' type="radio" id="rb1" value="M" />M
<input name='a' type="radio" id="rb2" value="L" />L
<input name='a' type="radio" id="rb3" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb2" value="Two"/>Two
<span class="teethproblem2">
<input name='b' type="radio" id="rb4" value="M" />M
<input name='b' type="radio" id="rb5" value="L" />L
<input name='b' type="radio" id="rb6" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb3" value="Three"/>Three
<span class="teethproblem3">
<input name='c' type="radio" id="rb7" value="M" />M
<input name='c' type="radio" id="rb8" value="L" />L
<input name='c' type="radio" id="rb9" value="C" />C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb4" value="Four"/>Four
<span class="teethproblem4">
<input name='d' type="radio" id="rb10" value="M" />M
<input name='d' type="radio" id="rb11" value="L" />L
<input name='d' type="radio" id="rb12" value="C" />C
</span>
</li>
<li><input type="button" onclick="getvals()" value="SAVE"></li>
</ul>
</form>
Highly Recommended Reading: Decoupling Your HTML, CSS, and JavaScript.
One of the biggest problems you'll run into, is example code that only works with the current html. If you decide to change that html in just about any way, your code stops working (aka software brittleness). The following code extensible (meaning adding more checkboxes/radios will be easy to add, probably requiring no code changes), and should be easy to understand. Removing li or adding more html won't cause this code to stop working because it doesn't rely on html structure.
$(document).ready(function() {
$('.js-save').on('click', function(e) {
var $btn = $(e.currentTarget);
var $form = $btn.closest('form');
var $pre = $('.debug');
$pre.text('');
$form.find('input:not(".ignore-value")').each(function(_,input) {
var $input = $(input);
var value = $input.val();
if ($input.is('[type=checkbox]')) {
value = $input.prop('checked');
}
var name = $input.prop('name');
$pre.append('name: ' + name + ':' + value + '\n');
if ($input.hasClass('js-associate-value') && value) {
var associatedValue = $($input.data('target')).val();
if (associatedValue) {
$pre.append(' - ' + associatedValue + '\n');
}
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<ul>
<li>
<input name='teeth' type="checkbox" id="cb1" value="One" class="js-associate-value" data-target="input[name=d]:checked"/>One
<span class="teethproblem1">
<input name='a' type="radio" id="rb1" value="M" class="ignore-value"/>M
<input name='a' type="radio" id="rb2" value="L" class="ignore-value"/>L
<input name='a' type="radio" id="rb3" value="C" class="ignore-value"/>C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb2" value="Two" class="js-associate-value" data-target="input[name=d]:checked"/>Two
<span class="teethproblem2">
<input name='b' type="radio" id="rb4" value="M" class="ignore-value"/>M
<input name='b' type="radio" id="rb5" value="L" class="ignore-value"/>L
<input name='b' type="radio" id="rb6" value="C" class="ignore-value"/>C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb3" value="Three" class="js-associate-value" data-target="input[name=c]:checked"/>Three
<span class="teethproblem3">
<input name='c' type="radio" id="rb7" value="M" class="ignore-value"/>M
<input name='c' type="radio" id="rb8" value="L" class="ignore-value"/>L
<input name='c' type="radio" id="rb9" value="C" class="ignore-value"/>C
</span>
</li>
<li>
<input name='teeth' type="checkbox" id="cb4" value="Four" class="js-associate-value" data-target="input[name=d]:checked"/>Four
<span class="teethproblem4">
<input name='d' type="radio" id="rb10" value="M" class="ignore-value" />M
<input name='d' type="radio" id="rb11" value="L" class="ignore-value" />L
<input name='d' type="radio" id="rb12" value="C" class="ignore-value" />C
</span>
</li>
<li><input class="js-save" type="button" name="submit" value="SAVE"></li>
</ul>
</form>
<pre class='debug'></pre>
I have a list of questions in HTML. Each question will have 4 radio buttons for the answers, and the user will select the appropriate answer. Each radio button has an assigned value. At the end, I would like to show in HTML, the user's score once the questions have all been answered.
It's fairly straight forward, but I am having issues iterating through the questions and returning a summing the total value for their score.
Any suggestions on the iterating jQuery loops would be helpful.
<div>
<p class="question">1. Question:</p>
<ul id="answers1">
<input type="radio" name="q1" value="15" id="q1a"><label for="q1a"> Answer 1</label><br/>
<input type="radio" name="q1" value="10" id="q1b"><label for="q1b"> Answer 2</label><br/>
<input type="radio" name="q1" value="5" id="q1c"><label for="q1c"> Answer 3</label><br/>
<input type="radio" name="q1" value="1" id="q1d"><label for="q1d"> Answer 4</label><br/>
</ul>
<p class="question">2. Question</p>
<ul id="answers2">
<input type="radio" name="q2" value="15" id="q2a"><label for="q2a"> Answer 1</label><br/>
<input type="radio" name="q2" value="10" id="q2b"><label for="q2b"> Answer 2</label><br/>
<input type="radio" name="q2" value="5" id="q2c"><label for="q2c"> Answer 3</label><br/>
<input type="radio" name="q2" value="1" id="q2d"><label for="q2d"> Answer 4</label><br/>
</ul>
<p class="question">3. Question</p>
<ul id="answers3">
<input type="radio" name="q3" value="1" id="q3a"><label for="q3a">Answer 1</label><br/>
<input type="radio" name="q3" value="5" id="q3b"><label for="q3b">Answer 2</label><br/>
<input type="radio" name="q3" value="10" id="q3c"><label for="q3c">Answer 3</label><br/>
<input type="radio" name="q3" value="15" id="q3d"><label for="q3d">Answer 4</label><br/>
</ul>
<div id="sum" >Print Score from Questions Here</div>
</div>
You can get total score usong this.
var score=0;
$("input[type='radio']:checked").each(function () {
score += $(this).val();
});
$('#sum').text(score);
I am making a simple quiz to get the number of correct questions answered by a person when he submits the 'submit' button. But, it is always giving Zero. Pls help.
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('[name=q1]').val() == "Delhi"){count++;}
if($('[name=q2]').val() == "Lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
It is always giving '0', but if I select 'Delhi' and 'Lotus' it should give answer as 2.
Two things:
$('[name=q1]').val() will give you the value of the first element with name="q1", not the checked element. For that, add :checked.
You're comparing "delhi" with "Delhi"; case matters.
$(document).ready(function() {
$('button').click(function() {
var count = 0;
if ($('[name=q1]:checked').val() == "delhi") {
count++;
}
if ($('[name=q2]:checked').val() == "lotus") {
count++;
}
alert(count);
});
});
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
You have an error in your Js code, and you have to select the checked inputs, your code selects just the first input
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('input[name=q1]:checked').val() == "delhi"){count++;}
if($('input[name=q2]:checked').val() == "lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
</body>
$(document).ready(function(){
$('button').click(function(){
var count = 0;
if($('[name=q1]:checked').val() == "delhi"){count++;}
if($('[name=q2]:checked').val() == "lotus"){count++;}
alert(count);
});
});
<body>
<div>
<p>Question: What is capital of India?</p>
<input type="radio" name="q1" value="delhi"> Delhi
<input type="radio" name="q1" value="mumbai"> Mumbai
<input type="radio" name="q1" value="kolkata"> Kolkata
<input type="radio" name="q1" value="lucknow"> Lucknow
</div>
<div>
<p>Question: What is the national flower of India?</p>
<input type="radio" name="q2" value="rose"> Rose
<input type="radio" name="q2" value="lotus"> Lotus
<input type="radio" name="q2" value="sunflower"> Sunflower
<input type="radio" name="q2" value="tulip"> Tulip
</div>
<button>submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
Try to rename you values with a capital letter (lotus=>Lotus, etc).
I want to make a questionnaire that asks questions then has a button at the end of the page called "display answers" which will show the user which answers they got correct.
If I were to use this question for example:
<p class="question">1. What is the answer to this question?</p>
<ul class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
</ul>
How would I go about creating a button for this code that when pressed, tells if the answer is correct or not?
<p class="question">1. What is the answer to this question?</p>
<ul id="answers" class="answers">
<input type="radio" name="q1" value="a" id="q1a"><label for="q1a">Answer 1</label><br/>
<input type="radio" name="q1" value="b" id="q1b"><label for="q1b">Answer 2</label><br/>
<input type="radio" name="q1" value="c" id="q1c"><label for="q1c">Answer 3</label><br/>
<input type="radio" name="q1" value="d" id="q1d"><label for="q1d">Answer 4</label><br/>
<input type="button" value="submit" onClick="showAnswer()" />
</ul>
<span id="info"></span>
Then add a script above that piece of code:
<script>
function showAnswer(){
if(document.getElementById('q1a').checked){
document.getElementById('info').innerHTML = "Correct!";
}else{
document.getElementById('info').innerHTML = "Incorrect!";
}
}
</script>
I don't know the answer to your quiz, so answer 1 is correct in this case.
Two .addEventListeners()
One on the container that holds all of the questions and answers (e.g. #QA1)
The other on the button used when finished with the quiz (e.g. #btn1)
When the user picks an answer, #QA1 will listen for any clicks on any radio button (e.g. .answers). Using a single event listener for multiple event.targets (i.e. the element clicked) is far more efficient than adding one on each radio button. Through comparing what was actually clicked (radio button) and what was the element with the listener, we'll can get the radio button's id. See this article for details.
Once the id of the clicked radio button is determined (see previous reference), it's pushed to an array (e.g. answers[]).
When the user is done, he/she clicks the "DONE" button, triggering the click event of #btn1.
A for loop is used to iterate over the answer[] and key[] arrays. On each iteration (i.e.loop,) the two are compared for matching elements.
The results are printed on #out1 which is an <output> element nested in an ordered list (<ol>).
Snippet
var qa = document.getElementById('QA1');
var btn1 = document.getElementById('btn1');
var answers = [];
var key = ['q1c', 'q2a', 'q3d'];
qa.addEventListener('click', function(event) {
if (event.target != event.currentTarget) {
var choice = event.target.id;
answers.push(choice);
}
event.stopPropagation();
}, false);
btn1.addEventListener('click', function(event) {
event.preventDefault();
var qList = document.getElementsByClassName('question');
var out1 = document.getElementById('out1');
for (var i = 0; i < qList.length; i++) {
if (answers[i] === key[i]) {
out1.innerHTML += '<li>' + answers[i] + ' is correct</li>';
} else {
out1.innerHTML += '<li>' + answers[i] + ' is incorrect, the correct answer is ' + key[i] + '</li>';
}
}
}, false);
body {
font: 400 16px/1.45'Verdana';
}
* {
font: inherit;
}
.question {
margin-bottom: 15px;
}
.answers {
list-style: none;
}
.answers li {
margin-left: -15px;
}
input[type="radio"] {
position: relative;
top: 2.25px;
}
#btn1 a {
text-decoration: none;
}
#out1 {
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<ol id="QA1" class="QA">
<li id="q1" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q1" value="a" id="q1a" />
<label for="q1a">Answer</label>
</li>
<li>b.
<input type="radio" name="q1" value="b" id="q1b" />
<label for="q1b">Answer</label>
</li>
<li>c.
<input type="radio" name="q1" value="c" id="q1c" />
<label for="q1c">Answer</label>
</li>
<li>d.
<input type="radio" name="q1" value="d" id="q1d" />
<label for="q1d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
<li id="q2" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q2" value="a" id="q2a" />
<label for="q2a">Answer</label>
</li>
<li>b.
<input type="radio" name="q2" value="b" id="q2b" />
<label for="q2b">Answer</label>
</li>
<li>c.
<input type="radio" name="q2" value="c" id="q2c" />
<label for="q2c">Answer</label>
</li>
<li>d.
<input type="radio" name="q2" value="d" id="q2d" />
<label for="q2d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
<li id="q3" class="question">What is the answer to this question?
<ol class="answers">
<li>a.
<input type="radio" name="q3" value="a" id="q3a" />
<label for="q3a">Answer</label>
</li>
<li>b.
<input type="radio" name="q3" value="b" id="q3b" />
<label for="q3b">Answer</label>
</li>
<li>c.
<input type="radio" name="q3" value="c" id="q3c" />
<label for="q3c">Answer</label>
</li>
<li>d.
<input type="radio" name="q3" value="d" id="q3d" />
<label for="q3d">Answer</label>
</li>
</ol>
<!--answers-->
</li>
<!--question-->
</ol>
<!--QA-->
<button id="btn1">DONE
</button>
<ol>
<output id="out1"></output>
</ol>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Questionare</title>
</head>
<body>
<p>1. What is the answer to this question?</p>
<ul onclick="man()">
<input type="radio" name="q1" value="a">Answer 1<br/> <input type="radio" name="q1" value="b">Answer 2<br/>
<input type="radio" name="q1" value="c">Answer 3<br/>
<input type="radio" name="q1" value="d">Answer 4<br/>
</ul>
<p id="m"></p>
<script>
var man = function(){
document.getElementById("m").innerHTML = 'The correct answer is: Answer 1';
}
</script>
</body>
</html>
Here is what u want, done in simplest way, using CSS Document object model, for reference go here HTML CSS DOM