[英]Input Number Max not working using Jquery dynamically
创建了一个简单的Input并尝试使用Jquery设置Max值。 最初,它将值设置为77,然后将最大值减小为50。
以下示例有效!
$(document).ready(function () { minMaxAge("#test-input",0,77) minMaxAge("#test-input",0,50) //Text Box max is now 50 // Working }); function minMaxAge(id,min,max) { $(id).change(function() { if ($(this).val() > max) { $(this).val(max); } else if ($(this).val() < min) { $(this).val(min); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="test-input" type="number" />
现在使用相同的示例,但是将最大值从77增加到79。
下面的示例不起作用。
$(document).ready(function () { minMaxAge("#test-input",0,77) minMaxAge("#test-input",0,79) //Text Box max is now 79 // Not Working }); function minMaxAge(id,min,max) { $(id).change(function() { if ($(this).val() > max) { $(this).val(max); } else if ($(this).val() < min) { $(this).val(min); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="test-input" type="number" /
我是通过Jstepper.Js库实现的,但是也遇到了类似的问题。 减小最大值时效果很好,但增大最大值时不起作用。
参考: Jstepper库
更新:
请检查更新的代码段。
$(document).ready(function() { $('input:radio[name="input-max"]').change( function() { if ($(this).is(':checked')) { var min = 0; var max = $(this).val(); minMaxAge("#test-input",0,max) } }); }); function minMaxAge(id, min, max) { $(id).change(function() { if ($(this).val() > max) { $(this).val(max); } else if ($(this).val() < min) { $(this).val(min); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p> Have two Radio button and they have set the max number to be entered in the Input. </p> <input type="radio" id="input-max1" name="input-max" value=77>Max 77<br> <input type="radio" id="input-max2" name="input-max" value=79> Max 79<br> <input id="test-input" type="number" />
您将在每个示例中创建两个change
。 第一个示例具有以下操作顺序:
第二个示例具有以下操作顺序:
在第二个示例中,当您将其与79进行比较时,该数字将永远不会大于77。
通过将最大值设置为77 和 79,可以有效地将其设置为77。如果要将最大值设置为79,只需将其设置为79:
$(document).ready(function () {
minMaxAge("#test-input",0,79);
});
您的方法的问题在于,您确实没有很好的方法来维护事件处理程序序列运行时所发生事件的上下文。 如果这样做,我将只有一个事件处理程序,并让minMaxAge()
函数调整最小值和最大值。 像这样:
function minMaxAge(id, min, max) {
var $element = $(id);
if (!$element.hasClass("handler-added")) {
// need to initialize the "change" event handler
$element.addClass("handler-added")
.on("change", function() {
var max = $element.data("max"), min = $element.data("min");
if (+$element.val() > max)
$element.val(max);
else if (+$element.val() < min)
$element.val(min);
});
}
// update min and max
if ($element.data("min") == null || +$element.data("min") > min)
$element.data("min", min);
if ($element.data("max") == null || +$element.data("max") < max)
$element.data("max", max);
);
该方法只添加一次“更改”事件处理程序。 之后,对minMaxAge()
后续调用将更新保留在jQuery .data()
属性中的最小和最大限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.