我有两个值select和number
<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>发布于 2020-07-30 22:42:44
您当前的代码应该可以很好地工作,但是,因为您的表单在默认情况下选择了product-1,所以您需要确保使用.change()在DOM ready上触发更改事件。这样,默认选择与max和min值将保持一致。
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" />
https://stackoverflow.com/questions/63175166
复制相似问题