简体   繁体   中英

JQuery Validate Input on Button Toggle

I'm using Jquery Validate in my web form. I have an empty input, however the input is populated dynamically with text on the click of a button. Validation doesn't seem to work when I do this.

  • when the input is empty, on submit validation works (input turns red).
  • when input is populated dynamically, it stays red, it should turn green

My code is below and here's a fiddle ;

In the fiddle, click submit when the input is empty, then toggle the button to No - the input should change to green without having to submit the form again.

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>

Jquery

$(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
    });
  }
});

You use some custom highlight and unhighlight on the control-group .

Just add this to the checked==true condition:

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

Since the rule is removed, it is not re-validated...

Your Fiddle updated .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM