簡體   English   中英

根據選中的單選按鈕設置最小值和最大值

[英]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>&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;">

我想這就是你要找的。

$("#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>&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;">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM