计算动态输入字段数之间的百分比

Calculate percentage between dynamic number of inputfields

本文关键字:之间 百分比 字段 动态 输入 计算      更新时间:2023-09-26

我需要显示每个输入值在完整数据集中所占的百分比。

如果用户输入3,2,1。"percent"输入字段应该显示"50,30和20"

问题是,我不知道表单会得到多少输入。可以是1到任意数

html源代码是由我创建的部分视图创建的。输出为:

<table>
    <tr>
        <th>Name</th><th>Distributiob key</th><th>Percent</th>
    </tr>
<tr>
    <td>
        House 1
    </td>
    <td>
        <input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
    </td>
    <td>
        <input type="text"  size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
    </td>
</tr>
<tr>
    <td>
        House 2
    </td>
    <td>
        <input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
    </td>
    <td>
        <input type="text"  size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
    </td>
</tr>
<tr>
    <td>
        House 3
    </td>
    <td>
        <input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
    </td>
    <td>
        <input type="text"  size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
    </td>
</tr>

表中的第一个字段是标题或名称。其次是用户输入分配号码的地方。第三个是readonly字段,其中包含计算出的百分比。

计算应该在javascript中完成,但我不能完全破解如何开始,获取输入和设置输出的坚果

这样的函数应该会有所帮助(这将四舍五入百分比-如果您想以不同的方式处理,请替换Math.floor):

function calcPcts() {
    var distributions = $("[id$=DistributionKey]");
    // Get the base first
    var base = 0;
    distributions.each(function () {
        base += window.parseInt($(this).val(), 10);
    });
    // Now calculate the percentages of the individual ones
    distributions.each(function () {
        var input = $(this),
            val = window.parseInt($(this).val(), 10),
            pct = (val === 0) ? val : Math.floor((val / base) * 100);
        $("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
    });
}

如果您在输入字段中添加了一个类,您可以使用jQuery获得带有该类的项的数量。然后,您可以获取值并执行计算。

下面是一个例子:

var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
    var total = GetTotal();
    for (i = 0; i < inputCount; i++) {
        var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
        if (total != 0) {
            var percent = inputValue / total;
            $('#LightPhysicalEntities_' + i + '__Percent').val(percent);
        }
    }
});
function GetTotal() {
    var total = 0;
    for (i = 0; i < inputCount; i++) {
        var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
        total += parseInt(inputValue);
    }
    return total;
}
下面是一个脚本工作的例子:http://jsfiddle.net/ZWuQr/