Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

javascript - JQuery sum using checkbox value and textbox value

How could I get the Final Total based on the sum of a checkbox value and the contents of a textbox?

JSFiddle example

My HTML:

<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td><td>10<input id="os1" type="text"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td><td>20<input id="os2" type="text" ></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td><td>Total2<input id="total2" type="text" readonly></td></tr>
</table>
Final Total<input type="text" id="final" readonly >

And Javascript:

$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});

if (total == 0) {
$('#total1').val('');
}
else {
$('#total1').val(total);
}
});



$('#os1, #os2').on('input',function(){
var os1= parseFloat($('#os1').val()) || 0;
var os2= parseFloat($('#os2').val()) || 0;

$('#total2').val(os1 + os2); 

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just bind a focus event and do it -

$('#final').bind('focus',function(){
    $(this).val(parseInt($('#total1').val())+parseInt($('#total2').val())); 
                         });

LIVE http://jsfiddle.net/mailmerohit5/h43te3z6/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...