首页 > 解决方案 > 根据选中的单选按钮设置最小值和最大值

问题描述

我有这 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>&nbsp;&nbsp;
<label><input type="radio" id="amt" name="discountType" value="amt" />Amount</label>

<br><br>

<input type="number" id="amount" name="amount" style="width:150px;">

标签: javascriptjquery

解决方案


我想这就是你要找的。

$("#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的值。您可能还想对负数强制执行相同的规则,您现在可能知道该怎么做了。


推荐阅读