开发者

jquery - calculate percentage for each value

I have a function that need to sum up from each input but at the same time every input must show the percentage. I have found the way to sum the value but I am having problem to show the percentage. Below is th开发者_如何学运维e HTML code:

Price 1: <input type="text" name="price01" class="price" />
Percentage 1: <span class='p'></span>
<br/>
Price 2: <input type="text" name="price02" class="price" />
Percentage 2: <span class='p'></span>
<br/>
Price 3: <input type="text" name="price03" class="price" />
Percentage 3: <span class='p'></span>
<br/>
Price 4: <input type="text" name="price04" class="price" />
Percentage 4: <span class='p'></span>
<br/>
Total: <span class="total"></span>

The jquery code I found in internet:

$.fn.sumValues = function() {
    var sum = 0;
    this.each(function() {
        if ( $(this).is(':input') ) {
            var val = $(this).val();
        } else {
            var val = $(this).text();
        }
        sum += parseFloat( ('0' + val).replace(/[^0-9-\.]/g, ''), 10);
    });
    return sum;
};

$(document).ready(function() {
    $('input.price').bind('keyup', function() {
        $('span.total').html( $('input.price').sumValues() );
    });
});

Hope anyone can help... Thank you.


Thank you, guys. I think I have solved the problem. It may not be the best solution but I get the idea and it works. Thank you again :)

The solution code: http://jsfiddle.net/amaleen123/6jnKf/2/


I don't know the sytax of javascript so my answer might not be too helpful but all you should need to do is after you calculate the total/sum, do each value divided by the total which wil give you the percent and put that value in the appropriate span.

Hope that helps even without any actual code.


This works

$(document).ready(function() {

    var $prices = $('input.price');

    $prices.bind('keyup', function() {
        var sum = $prices.sumValues();
        $('span.total').html( sum );

        $('.p').each(function(i,e){
           $(e).text( $prices.eq(i).val() / sum );
        });
    });
});

Basically, every thime a keyup event is triggered and after sumValues is called, you need to iterate over those elements again to compute the respective percentages.

This is by no means, the most efficient solution, but it gets the job done while you improve it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜