How to Sum Multiple Same Class Input Values by jQuery

jQuery is very cool library, you can do so many things faster than normal javascript, here is one example: If you have multiple input and all of them have same class, you can sum of their value and more. “each” function does everything. Take a look at codes below.

Script


<script type="text/javascript">
function sum(classname)
 {
    $("."+classname+"sum").val(0);
    var sum = 0;
    $("."+classname).each(function()
       {
          if(!isNaN(this.value) &&  this.value.length!=0)
             {
                sum += parseFloat(this.value);
             }
        });

   $("."+classname+"sum").val(sum);
 }
</script>

Html


Sum:<input type="text" />
Value1:<input type="text" />
Value2:<input type="text" />
Value3:<input type="text" />
Value4:<input type="text" />
<input onclick="sum('classname');" type="button" value="Sum" />

Download Source Demo

, ,

No comments yet.

Leave a Reply