Reputation: 73
My HTML code :
$(":checkbox").change(function() {
var arr = $(":checkbox:checked").map(function() {
return $(this).next().text();
}).get();
var myVal = $(":checkbox:checked").map(function() {
return ($(this).attr('data-marks'));
}).get();
var myPoint = $(":checkbox:checked").map(function() {
var sum = 0;
var count = parseFloat($(this).attr('data-marks'));
sum = sum + count;
return sum;
}).get();
$("#myDiv, #myTop").html(arr.join('<br><br>'));
$('#myVal').html(myVal.join('<br><br>'));
$('#totalGrade').text(myPoint);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><input id="c1" data-marks="20" type="checkbox" /><label for="c1">abc</label></li>
<li><input id="c1" data-marks="15" type="checkbox" /><label for="c1">xyz</label></li>
<li><input id="c1" data-marks="30" type="checkbox" /><label for="c1">pqr</label></li>
<div id="myDiv"></div>
<div id="myMarks"></div>
<div id="total"></div>
Here, I am copying the content(i.e. abc,xyz,pqr) and marks(20,15,30) relative to input checkbox into another div.While I am trying to get the respective sum of marks into the third div(i.e. total), it is coming up as a string. I am getting value as 201530 during checkbox event. What am I missing here?
Upvotes: 1
Views: 19
Reputation: 67505
You could get the total using map
and a variable total
:
$(":checkbox:checked").map(function() {
total+=parseFloat($(this).attr('data-marks'));
})
Append total to #total
:
$('#total').text(total);
Hope this helps.
$(":checkbox").change(function() {
var total=0;
var arr = $(":checkbox:checked").map(function() {
return $(this).next().text();
}).get();
$(":checkbox:checked").map(function() {
total+=parseFloat($(this).attr('data-marks'));
})
$("#myDiv, #myTop").html(arr.join('<br><br>'));
$('#total').text(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li><input id="c1" data-marks="20" type="checkbox" /><label for="c1">abc</label></li>
<li><input id="c1" data-marks="15" type="checkbox" /><label for="c1">xyz</label></li>
<li><input id="c1" data-marks="30" type="checkbox" /><label for="c1">pqr</label></li>
<div id="myDiv"></div>
<div id="myMarks"></div>
<div id="total"></div>
<div id="myVal"></div>
<div id="totalGrade"></div>
Upvotes: 1