开发者

Control a dynamically created <input />s (like name[]) doesn't sum more than 99, jQuery

I've got a backend page where the client can add dynamically various <input />s for declaring the percentage of participation of other people. Like: Company A colaborates with Company B and C that B has 10% and the C the 30%. Company A will have 60%.

The exactly <input /> is this:

<input type="text" name="percentage[]" value="0" /> %

There is another one for the name of the company, but this doesn't needs any kind of control.

Now, when the user is filling the data and adds percentage, I've to calculate that the sum of all percentage[] it's less or equal to 99. I've to show on a <div /> the participation of company A depending of the percentage[] introduced and if the sum of percentage[] is =99 I can't let the user introduce bigger numbers on percentage[] inputs.

Example #1:

  • Company B: 10%
  • Company C: 30%
  • Company D: 10%

Total participation of Company A is 50%.

Example #2:

  • Company B: 50%
  • Com开发者_如何转开发pany C: 49% <- the user can't put a number bigger than 49% because Company A will at least have a 1% of the participation.
  • Company D: 0% <- can't have more percentatge

Total participation of Company A is 1%.

First of all I know that I've to use .live() to handle this because is added in the DOM after the document.ready(). When typing, I assume that I've to check the sum every number and finally write to the div the percentage for company A depending on the array of percentage[].

Can someone help me with this?

Thank you in advance!


add a class to your input for easier selection: <input type="text" name="percentage[] class="percentage" value="" />

then:


 $('.percentage').each(function(){ 
    $(this).change(function(){ 
        var sum = 0; 
        $('.percentage').each(function(){ sum += $(this).val(); }); 
        alert(sum); 
    });
 });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜