有两个字段,第一个字段discountType
和discountAmount
。我想要实现的是:如果 discountType
等于 percentage
输入 discountAmount
只接受 0 到 100 之间的数字。如果 discountType
等于 absolute
discountAmount
中应接受任何数字。
我看过两个类似的问题here和 here并尝试使用 prop()
和 attr()
方法,但没有成功。
我的代码目前看起来像这样(使用 .prop()
):
HTML
<div class="container">
<div class="form-group">
<label class="form-control-label required" for="coupon_discountType">Discount type
</label>
<select id="coupon_discountType" name="coupon[discountType]" class="form-control">
<option value="percentage">percentage</option>
<option value="absolute">absolute</option>
</select>
</div>
<div>
<label for="coupon_discountAmount" class="form-control-label required">Amount
</label>
<div class="input-group">
<div class="input-group-prepend" id="absolute">
<span class="input-group-text">€</span>
</div>
<input type="text" id="coupon_discountAmount" name="coupon[discountAmount]" required="required" class="form-control" />
<div class="input-group-append" id="percentage">
<span class="input-group-text">%</span>
</div>
</div>
</div>
</div>
jQuery
$("#coupon_discountType").change(function() {
if($(this).val() === 'percentage') {
$("#coupon_discountAmount").prop('max', 100);
$('#absolute').hide();
}
else {
$('#absolute').show();
}
if($(this).val() === 'absolute') {
$('#percentage').hide();
}
else {
$('#percentage').show();
}
}).change();
或者一个JSFiddle
最佳答案
看看下面的 JSFIDDLE:
01) Fiddle with input type as number
02) Fiddle with input type as text
JS代码:
在下面的代码中,检查了“coupon_discountAmount”字段是否具有属性“max”或“min”。如果它们存在并且输入的值不在指定的“最大”或“最小”范围内,则只需将“coupon_discountAmount”中的值更改为相应的“最大”或“最小”值。
$("#coupon_discountAmount").change(function(event){
// restricting to max value specified
if( typeof $(this).attr('max') != 'undefined' ) {
if( !isNaN($(this).val()) && (parseInt($(this).val()) > $(this).attr('max')) ) {
$(this).val($(this).attr('max'));
}
}
// restricting to min value specified
if( typeof $(this).attr('min') != 'undefined' ) {
if( !isNaN($(this).val()) && (parseInt($(this).val()) < $(this).attr('min')) ) {
$(this).val($(this).attr('min'));
}
}
});
希望我说对了,这就是您在答案中寻找的内容。
关于javascript - 其他字段条件下的 jQuery 最大值输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53540058/