【问题标题】:Using Jquery to set required based on input value使用Jquery根据输入值设置required
【发布时间】:2020-06-20 11:47:00
【问题描述】:

如果另一个输入的值大于 8,我想更改 HTML 输入的 required 属性。(不提交任何内容)

<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">

基本上如果 inputCheck 的值大于 8,则将 inputReact 的 rquired 设置为 true。我知道如何更改属性,问题是检查值而不提交。

【问题讨论】:

    标签: javascript jquery html validation input


    【解决方案1】:

    你可以使用input监听器

    let checkBox = document.getElementById("inputCheck")
    , textBox = document.getElementById("inputReact")
    
    checkBox.addEventListener("input", evt => {  
      if(evt.target.value > 8) textBox.setAttribute("required", true)
      else textBox.removeAttribute("required")
    })
    <input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
    <input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">

    【讨论】:

      【解决方案2】:

      将更改事件侦听器添加到所需的输入字段。

      $('#inputCheck').change(function() {
          const value = $(this).val();
          const rInput$ = $('#inputReact');
          if(value > 8) { // could also use parseInt(value) to convert value into number if it isn't already.
              rInput$.attr('required', true); 
          } else {
              rInput$.removeAttr('required');
          }
      });
      

      【讨论】:

      • 很酷,但是您在 jquery 中请求答案并接受了纯 JS 答案:) 只是说,没有难过的感觉。
      • 这是第一个来的,所以我就接受了,以前从未发布过。不过我用过你的。
      【解决方案3】:

      <!doctype html>
      <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>keydown demo</title>
       
        <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
      </head>
      <body>
       
      <form>
       <input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
      <input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">
      </form>
      
       
      <script>
      var xTriggered = 0;
      $(document).ready(function()
      {
      alert("ok");
      $( "#inputCheck" ).keydown(function( event ) {
      
       var myLength = $("#inputCheck").val().length;
      
      if((myLength+1) > 8)
      {
      
      $("#inputReact").attr("required","true");
      }
      });
       
      });
      </script>
       
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-01-29
        • 2011-02-19
        • 2011-06-15
        • 2016-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多