Javascript 如何通过选择值使数值最小值/最大值发生变化?

Javascript 如何通过选择值使数值最小值/最大值发生变化?,javascript,jquery,Javascript,Jquery,我有两个值选择和数字 <select id="select-1" name="select-1" > <option value="product-1">Product 1</option> <option value="product-2">Product 2</option> </select> <input type="nu

我有两个值选择和数字

<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 ready with.change上触发更改事件。这样,默认选择与最大值和最小值将保持一致

jQuerydocument.readyfunction{ jQuery'select-1'。关于'change',函数{ 如果this.value=='product-1'{ jQuery'field-number-1'。attr'min','100'; jQuery'field-number-1'。attr'max','200'; }else ifthis.value==“产品-2”{ jQuery'field-number-1'。attr'min','300'; jQuery'field-number-1'。attr'max',500'; }否则{ jQuery'field-number-1'。attr'min','100'; jQuery'field-number-1'。attr'max',500'; } //报告当前值是否有效 jQuery'field-number-1'[0]。报告有效性; //删除此…仅用于测试 console.log jQuery'field-number-1'[0]; } 改变 jQuery'field-number-1'。在'input'上,函数e{ console.log this.checkValidity; 如果!这个。检查有效性{ this.setCustomValidity`提供介于${$this.attr'min}和${$this.attr'max}之间的数字; 这就是报告的有效性; }否则{ 这是有效性; 这就是报告的有效性; } }; }; 产品1 产品2
select-1看起来应该是select-1-field,forminator-field-number-1应该是field-number-1。否则,代码段中不存在这些ID。您使用forminator-field-number-1指的是什么?这在你的HTML中没有出现。更改但不解决问题最小值=100最大值=200已设置,但为什么我可以键入小于100或大于200,如何解决这一问题这是一个很好的问题,但它与你在问题中描述的问题不同。你能帮我解决它吗,因为最小值为100,如果我输入50,则必须将值更改为100,以便与@jeff78592251集成,这就是这种类型的客户端验证的工作方式。该行为不是更改“最小”和“最大”属性的结果。这是默认行为。为了防止输入无效的输入,您必须在侦听所有可能事件的基础上创建自定义验证解决方案。。。。。我的答案中的修改只是警告,不会阻止您键入内容,但如果您粘贴输入内容或使用箭头更改输入内容,则不会收到警告。