javascript - 根据选中的单选按钮设置最小值和最大值
问题描述
我有这 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的值。您可能还想对负数强制执行相同的规则,您现在可能知道该怎么做了。
推荐阅读
- google-cloud-ml - Google Cloud ML 使用对象检测模型返回空预测
- identityserver4 - 允许使用 JWT Claim 访问多个公司
- mysql - 由于数据类型,“字段列表”中的未知列“”
- python - 从列表连接到for循环的格式化字符串(python)
- apache-spark - AWS Glue 与 AWS EMR - 在 Spark 作业中覆盖 S3 文件
- javascript - 如何在 Angular 5 的一个组件中使用多个模板 URL?
- c++ - 获取csv文件中行数的最快方法是什么?
- amazon-web-services - 使用 SNS 通知自动停止 RDS 实例
- ruby-on-rails - ruby 刷新连接字段
- android - 我的 Nougat 设备上的可用 RAM