javascript - 如何通过选择值改变数值最小值/最大值?
问题描述
我有两个值选择和数字
<select id="select-1" name="select-1" >
<option value="product-1">Product 1</option>
<option value="product-2">Product 2</option>
</select>
<input type="number" name="number-1" id="field-number-1" pattern="^\-?\d*([\.\,]\d+)?" inputmode="numeric" min="100" max="500" />
使用 jQuery 尝试通过选择不同的产品来更新最小值/最大值,但它不会更新数值
<script type='text/javascript'>
jQuery(document).ready(function(){
jQuery('#select-1').on('change', function() {
if ( this.value == 'product-1') {
jQuery('#field-number-1').attr('min', '100');
jQuery('#field-number-1').attr('max', '200');
} else if(this.value == 'product-2') {
jQuery('#field-number-1').attr('min', '300');
jQuery('#field-number-1').attr('max', '500');
} else {
jQuery('#field-number-1').attr('min', '100');
jQuery('#field-number-1').attr('max', '500');
}
});
});
</script>
解决方案
您当前的代码应该可以正常工作,但是由于您的表单默认加载为product-1
选中状态,因此您需要确保在 DOM 上触发 change 事件.change()
。这样,默认选择和max
andmin
值将是一致的。
jQuery(document).ready(function(){
jQuery('#select-1').on('change', function() {
if ( this.value == 'product-1') {
jQuery('#field-number-1').attr('min', '100');
jQuery('#field-number-1').attr('max', '200');
} else if(this.value == 'product-2') {
jQuery('#field-number-1').attr('min', '300');
jQuery('#field-number-1').attr('max', '500');
} else {
jQuery('#field-number-1').attr('min', '100');
jQuery('#field-number-1').attr('max', '500');
}
//Report if current value is valid
jQuery('#field-number-1')[0].reportValidity();
//delete this .... just for testing
console.log( jQuery('#field-number-1')[0] );
})
.change();
jQuery('#field-number-1').on('input', function(e) {
console.log( this.checkValidity() );
if( !this.checkValidity() ) {
this.setCustomValidity(`Provide a number between ${$(this).attr('min')} and ${$(this).attr('max')}`);
this.reportValidity();
} else {
this.setCustomValidity('');
this.reportValidity();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-1" name="select-1" >
<option value="product-1">Product 1</option>
<option value="product-2">Product 2</option>
</select>
<input type="number" name="number-1" id="field-number-1" pattern="^\-?\d*([\.\,]\d+)?" inputmode="numeric" min="100" max="500" />
推荐阅读
- django - 使用 Jinja / Django 显示 Algolia 结果
- php - 我的buddypress自定义标签代码有什么问题?
- php - 如何使用内容类型为 EAN-13 的 php 创建条形码
- python - 如何确定 sshd 的这个 perl 脚本的标准输入内容
- python - 仅将值复制到具有列名的新空数据框 - Pandas
- angular - 为 Angular 6 自定义 Angular Material Datepicker 大小
- angular - 如何不让 mat-sidenav-content 占用网页上的空白空间
- amazon-s3 - 从 MapR 到 Amazon S3 的数据迁移
- c# - C# 字符串中控制字符的转义码
- javascript - Array.from(Object) 和 [...Object] 有什么区别?