Reputation: 6264
i have form as shown in picture
what i need is, when i type/ change value in amount, it auto calculate sum at the bottom
also i don't want to let add any character...
Thanks
Upvotes: 3
Views: 25010
Reputation: 5007
Add class="calc"
to each of your amount input fields and add id="total"
to your total result element.
The jQuery Code:
$(document).ready(function(){
$('.calc').change(function(){
var total = 0;
$('.calc').each(function(){
if($(this).val() != '')
{
total += parseInt($(this).val());
}
});
$('#total').html(total);
});
})(jQuery);
and a sample HTML Code:
<input type="text" class="calc" value="">
<input type="text" class="calc" value="">
<input type="text" class="calc" value="">
<input type="text" class="calc" value="">
<input type="text" class="calc" value="">
<span id="total"></span>
Upvotes: 4
Reputation: 203
Demo : http://jsfiddle.net/merakli/vxXCK/4/
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="tr" lang="tr" dir="ltr">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-9" />
<style type="text/css">
<!--
html,body,div,span,h1,h2,h3,p,hr,br,img,form,input,ul,li,a {
margin:0;
padding:0;
border:0;
}
ul li {list-style:none;}
body {
font-family:Helvetica, Arial, Tahoma, sans-serif;
font-size:13px;
color:#444;
line-height:1.5em;
}
#kapsayici {
background:#fff;
margin:10px auto;
width:960px;
border:1px solid #dfdfdf;
min-height: 700px;
}
input {
border:1px solid #dfdfdf;
}
-->
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
<script type="text/javascript">
$.fn.fonkTopla = function() {
var toplam = 0;
this.each(function() {
var deger = fonkDeger($(this).val());
toplam += deger;
});
return toplam;
};
function fonkDeger(veri) {
return (veri != '') ? parseInt(veri) : 0;
}
$(document).ready(function(){
$('input[name^="fiyat"]').bind('keyup', function() {
$('#toplam').html( $('input[name^="fiyat"]').fonkTopla());
});
});
</script>
</head>
<body>
<div id="kapsayici">
<ul>
<li><input type="text" name="fiyat[]" /></li>
<li><input type="text" name="fiyat[]" /></li>
<li><input type="text" name="fiyat[]" /></li>
<li><input type="text" name="fiyat[]" /></li>
<li><input type="text" name="fiyat[]" /></li>
</ul>
Toplam: <span id="toplam"></span>
</div>
</body>
</html>
Upvotes: 2
Reputation: 7906
EDIT This one works better:
$('.amount').keyup(function() {
var result = 0;
$('#total').attr('value', function() {
$('.amount').each(function() {
if ($(this).val() !== '') {
result += parseInt($(this).val());
}
});
return result;
});
});
$('.amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('.amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
You have to add a class="amount"
to the input fields and id="total"
to the last field
Upvotes: 6