从一系列输入字段中获取最大值
Get max from series of input fields
我有一系列输入字段。我不知道有多少,所以我需要从类中获取值。在本例中,类是.total
。
bestresult
是一个文本字段,从mysql
获得它的值,但我希望它是手动更改或从其他文本字段的最高值。
这是代码。这显然不可行,但也许你知道我想做什么。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input.total').change(function()
{
var max = $('.total').max();
$('#bestresult').attr("value", max);
});
</script>
<body>
<form>
<input type="text" name="bestresult" id="bestresult" class="total" value=""><br>
<input type="text" name="resultat[100][total]" class="total" value=""><br>
<input type="text" name="resultat[121][total]" class="total" value=""><br>
<input type="text" name="resultat[130][total]" class="total" value="">
</form>
</body>
</html>
解决方案非常简单。试试这个:
$('input.total').change(function()
{
var max = 0;
$('.total').each(function(){
if(parseFloat($(this).val()) > max ) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
但是如果你有多个文本框,你应该跟踪最大值,并在每次触发更改事件时更新,以获得更好的性能。
var max = 0;
// get the max for the first time
$(document).ready(function () {
$('.total').each(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
});
$('#bestresult').val(max);
});
$('input.total').change(function () {
if (parseFloat($(this).val()) > max) {
max = parseFloat($(this).val());
}
$('#bestresult').val(max);
});
首先,您应该将脚本放在正文的末尾,以便在绑定更改事件时定义元素。
然后,您最好过滤输入,以排除包含max的输入。您可以使用此选择器:input.total[id!=bestresult]
。
最好也绑定keyup事件,这样最大值就会更新,而用户不必在外面点击。
因此,你可以有这样的代码:$('input.total[id!=bestresult]').on('blur change keyup', function(){
$('#bestresult').attr("value", Math.max.apply(null, $('.total[id!=bestresult]').map(function(){
return parseFloat(this.value)}).slice().filter(function(i, v){return v==v})
));
});
演示相关文章:
- 按最大值获取数组索引
- 从 JavaScript 中的数组中获取最大值和最小值
- 获取整数对象属性名称的最小值和最大值
- 从D3中的JSON中获取最大值
- 如何在JavaScript中从数组中获取最大值
- 从一个值数组中获取多个最大值
- JavaScript/Andercore获取对象中所有项的最小-最大值
- d3.js nvd3.js--获取y轴最小/最大值
- 如何获取数组中包含最大值的两个对象
- Javascript:如何获取输入范围内的最大值
- 在多维数组 JavaScript 或 coffeescript 中获取最大值
- 在格式化为 JSON 的变量中获取最大值
- 从geojson中获取最大值和最小值
- 使用javascript从JSON对象中获取最大值
- 从JS或jQuery中的数组中获取最大值
- 使用Javascript从多维数组中获取最大值
- 从带有函数和参数的关联数组中获取最大值或最小值
- JS中的变量,用于获取最大值的循环
- 从一系列输入字段中获取最大值
- 从JSON对象D3JS中获取最大值