【问题标题】:Disable one input field based on second input field entery根据第二个输入字段条目禁用一个输入字段
【发布时间】:2012-08-16 06:15:07
【问题描述】:

我有 2 个输入文本字段,当用户尝试在 A 输入文本字段中输入任何值时,B 输入字段需要禁用,不允许 B 字段中的任何条目。同样,如果用户尝试在 B 输入字段中输入任何输入,则需要禁用 A 输入字段。 谁能帮我用Jquery写代码

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    两个答案都是正确的,只是决定将代码简短:

        $('input.inputA').keyup(function () {
            $('input.inputB').prop('disabled', this.value.length === 0 ? false : true);
        });
    
        $('input.inputB').keyup(function () {
            $('input.inputA').prop('disabled', this.value.length === 0 ? false : true);
        });
    

    演示:http://jsfiddle.net/AnDxC/

    【讨论】:

      【解决方案2】:

      输入字段名称为AB

      $('input[name="A"]').on('change', function(){
          if($(this).val() !== ''){
              $('input[name="B"]').attr('disabled', 'disabled');
          }else{
              $('input[name="B"]').removeAttr('disabled');
          }
      });
      $('input[name="B"]').on('change', function(){
          if($(this).val() !== ''){
              $('input[name="A"]').attr('disabled', 'disabled');
          }else{
              $('input[name="A"]').removeAttr('disabled');
          }
      });
      

      【讨论】:

      • removeattr() 应该是 removeAttr()。没有骆驼箱就行不通。
      【解决方案3】:

      假设

      <input type="text" class="inputA" />
      <input type="text" class="inputB" />
      

      和 JS:

      $(function(){
          $("input").on("keyup", function(){
                  if($(this).hasClass("inputA") && $(".inputA").val()){
                     $("input.inputB").prop("disabled", true);
                     $("input.inputA").prop("disabled", false);
                  } else if($(this).hasClass("inputB") && $(".inputB").val()){
                     $("input.inputA").prop("disabled", true);
                      $("input.inputB").prop("disabled", false);
                  } else {
                             $(".inputA, .inputB").prop("disabled", false);
                          }
          });
      });
      

      JsFiddle

      【讨论】:

      • $('.inputA').val() 将返回 truey 和 falsey,因此不需要 ">0",除非这是某种性能问题。
      • 你错过了两个字段都为空的情况。
      【解决方案4】:

      如果你有下一个 HTML:

      <input type="text" name="test1" id="test1" value=""/>
      <input type="text" name="test2" id="test2" value=""/>
      

      我的解决办法是:

      <script>
      $(function(){
          $('#test1, #test2').keyup(function(){
              var $test1 = $('#test1');
              var $test2 = $('#test2');
              $test1.prop('disabled', $test2.val() && ! $test1.val());
              $test2.prop('disabled', $test1.val() && ! $test2.val());
          });
      });
      </script>
      

      这是example

      【讨论】:

        猜你喜欢
        • 2011-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        相关资源
        最近更新 更多