计算动态输入字段数之间的百分比
Calculate percentage between dynamic number of inputfields
我需要显示每个输入值在完整数据集中所占的百分比。
如果用户输入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/
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- 全局变量和全局对象的属性之间有什么区别吗
- java.net和javascript之间正则表达式的差异
- JavaScript中的函数和对象之间没有区别吗?
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- Jquery在函数之间传递表行
- 根据某些条件在视图之间切换
- 在控制器和数据对象之间同步数据
- 计算HTML表TD中两个数字之间的百分比
- 在谷歌地图 JS API 上获取两个点之间的点的纬度和经度(按百分比)
- 根据百分比计算两个坐标之间的点
- 计算动态输入字段数之间的百分比
- Highcharts共享的工具提示使系列之间的百分比差异
- 传递滚动值作为百分比作为参数,计算两点之间的距离
- 两个值之间的百分比差
- 百分比在0和100之间的javascript正则表达式
- 计算for循环中JSON中两个值之间的百分比
- Javascript逻辑获取两个数字之间每个数字的百分比
- FabricJS-在两点之间画一条线的百分比
- 删除剑道中百分比符号和数字之间的空格