首页 > 解决方案 > 如何通过选择值改变数值最小值/最大值?

问题描述

我有两个值选择和数字

<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>

标签: javascriptjquery

解决方案


您当前的代码应该可以正常工作,但是由于您的表单默认加载为product-1选中状态,因此您需要确保在 DOM 上触发 change 事件.change()。这样,默认选择和maxandmin值将是一致的。

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" />


推荐阅读