[英]Setting min and max value based on radio button checked
我有这 2 个单选按钮和数字输入。 如果检查单选percentage
,我想要实现的金额值不能超过 100。默认情况下,单选按钮将检查percentage
。 现在假设我检查了amount
并输入了一个超过 100 的值,然后我再次检查了percentage
,似乎金额值没有变为最大值。 而且,如果我检查百分比,我仍然可以输入超过 100 的金额吗?
$("#perc").prop('checked', true); $("#amount").attr({ "max": 100, "min": 0 }); $('input:radio[name="discountType"]').change(function () { if ($(this).val() == 'perc') { // alert('yo'); $("#amount").attr({ "max": 100, "min": 0 }); } });
<label><input type="radio" id="perc" name="discountType" value="perc" />Percentage</label> <label><input type="radio" id="amt" name="discountType" value="amt" />Amount</label> <br><br> <input type="number" id="amount" name="amount" style="width:150px;">
我想这就是你要找的。
$("#perc").prop('checked', true);
$("#amount").attr({"max": 100, "min": 0 });
$("#perc").click(() => {
if ($("#amount").val() > 100) $("#amount").val(100);
$("#amount").attr({"max": 100, "min": 0 });
});
$("#amt").click(() => {
$("#amount").removeAttr("max");
$("#amount").removeAttr("min");
});
$("#amount").change(() => {
if ($("#perc").prop('checked')) {
if ($("#amount").val() > 100) $("#amount").val(100);
}
});
每当检查百分比按钮时,它保持小于或等于100的值。 您可能还想对负数强制执行相同的规则,您现在可能知道该怎么做了。
这是你想要达到的目标吗?
$("#perc").prop('checked', true); $("#amount").attr({ "max": 100, "min": 0 }); $('#perc').click(function() { $("#amount").attr({ "max": 100, "min": 0 }); updateInput(); }); $('#amt').click(function() { $("#amount").attr({ "max": 9999999, "min": 0 }); updateInput(); }); $('input[type="number"]').on('input change keyup paste', function () { updateInput(); }); function updateInput() { var input = $('#amount')[0]; if (input.min) input.value = Math.max(parseInt(input.min), parseInt(input.value) || 0); if (input.max) input.value = Math.min(parseInt(input.max), parseInt(input.value) || 0); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label><input type="radio" id="perc" name="discountType" value="perc" />Percentage</label> <label><input type="radio" id="amt" name="discountType" value="amt" />Amount</label> <br><br> <input type="number" id="amount" name="amount" style="width:150px;">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.