我正在尝试将值分配到3个输入字段中,因此所有3的总和不能超过设置的动态值。我在JSFiddle中尝试过它工作正常。以下是演示:http://jsfiddle.net/k2QVV/
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
var
total = parseInt($('#quantityRequired').text()),
inputs = $('input[type="number"]');
inputs
.attr('max', total)
.change(function() {
//Make sure that current value is in range
if($(this).val() > parseInt($(this).attr('max'))) {
$(this).val($(this).attr('max'));
} else if ($(this).val() < parseInt($(this).attr('min'))) {
$(this).val($(this).attr('min'));
}
//Get currently available total
var current = available();
//Now update max on each input
$('input').each(function(indx) {
$(this).attr('max', parseInt($(this).val()) + total - current);
});
});
</script>
</head>
<body>
Quantity Required : <span id='quantityRequired'>20</span><br />
<input type='number' name='val1' min='0' value='0' required /> <br />
<input type='number' name='val2' min='0' value='0' required /> <br />
<input type='number' name='val3' min='0' value='0' required />
</body>
</html>
答案 0 :(得分:1)
您的代码适用于jsfiddle,因为在调用代码之前会加载jQuery lib。 您应该在调用脚本之前加载库,方法是添加以下行:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
之后:
<meta name="viewport" content="width=device-width, initial-scale=1.0">