javascript - Sum with jquery not working -
i have lot of labels shown on page. want sum values , store them in final_cpa
.
html :
<label class="tmpcpa">32.1</label>
js :
function calculate_final_cpa() { var final_cpa = 0; var allfilled = false; $('.tmpcpa').each(function () { if ($(this).val() != 0) { final_cpa += parseint($(this).text()) || 0; allfilled = true; } else { allfilled = false; } }); console.log(final_cpa); console.log(allfilled); } var run = setinterval(calculate_final_cpa, 500);
however final_cpa
0 , allfilled
remains false
.
that because label don't have value
attribute .val()
function return empty string, have use .text()
instead text content inside label element :
if ($(this).val() != 0) {
should :
if ($(this).text() != 0) {
note : rayon mentioned in comment below text()
return string
better change 0 in condition string '0'
.
hope helps.
function calculate_final_cpa() { var final_cpa = 0; var allfilled = false; $('.tmpcpa').each(function () { if ($(this).text() != '0') { final_cpa += parseint($(this).text()) || 0; allfilled = true; } else { allfilled = false; } }); console.log(final_cpa); console.log(allfilled); } calculate_final_cpa();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label class="tmpcpa">32.1</label>
Comments
Post a Comment