代码之家  ›  专栏  ›  技术社区  ›  TheOrdinaryGeek

JQuery在按钮切换时验证输入

  •  2
  • TheOrdinaryGeek  · 技术社区  · 6 年前

    我在用 Jquery Validate

    • 当输入为空时,提交验证工作(输入变为红色)。

    我的代码在下面,这里是一个 fiddle ;

    在fiddle中,当输入为空时单击submit,然后将按钮切换到 No

    HTML格式

    <p>Does this item have an inventory number?</p>
    <p>
      <form id="myForm" method="post">
        <input type="checkbox" class="input-large" value='1' name="btn" id="btn">
    
        <div class="control-group">
          <div class="controls">
            <div class="input-prepend">
              <input type="text" class="input-large" id="type" name="type" placeholder="Inventory Number">
            </div>
          </div>
        </div>
    
        <input type="submit" class="submit" value="Submit">
      </form>
    

    滑动分页

    $(function() {
      $('#btn').bootstrapToggle({
        on: 'No',
        off: 'Yes',
        onstyle: 'danger'
      });
    })
    $("#myForm").validate({
      rules: {
        type: {
          required: true,
          minlength: 2
        }
      },
      highlight: function(label) {
        $(label).closest('.control-group').addClass('error');
      },
      unhighlight: function(label) {
        $(label).closest('.control-group').addClass('success');
      },
    
    });
    $("#btn").on("change", function() {
      if ($(this).prop('checked') == true) {
        $("#type").attr("readonly", "true");
        $("#type").val("Personal Item");
        $("#type").rules("remove", "number minlength maxlength");
      }
      if ($(this).prop('checked') == false) {
        $("#type").removeAttr("readonly");
        $("#type").val("");
        $("#type").rules("add", {
          required: true,
          minlength: 5,
          maxlength: 6
        });
      }
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Louys Patrice Bessette    6 年前

    你用一些习惯 highlight unhighlight control-group

    把这个加到 checked==true 条件:

    $("#type").closest('.control-group').removeClass("error").addClass("valid");
    $("#type").next(".error").remove();
    

    你的 Fiddle updated .