Conditional jQuery validation based on custom attribute

Viewed 49

I'd like to enable/disable buttons on key up change conditionally based on a custom data attribute that matches between an input and a button. I've solved it with just one input, but it seems that when I add another one in the mix, the buttons don't seem to enable. Furthermore, I have a hunch that it's because of .each() but I can't put my finger on it.

Here's the CodePen I've tried and failed on

var validation = $('[data-validation]');
var validate;

validation.on("change keyup", function (e) {
  let validated = true;
  validation.each(function () {
    let value = this.value;
    validate = $(this).data('validation');
    
    if (value && value.trim() != "") {
      validated = false;
    } else {
      validated = true;
      return false;
    }
  });
  
  if (validated) {
    $('[data-validator=' + validate + ']').prop("disabled", true);
  } else {
    $('[data-validator=' + validate + ']').prop("disabled", false);
  }
});
1 Answers

The key here is to only run your validation code for the input that was changed. As opposed to what you have, which is to run for all inputs.

To get the input that actually changed, you can utilize the .target property of the event object passed to the event handler.

Alternatively, if you remove the validation.each() entirely, it also works. That is because jQuery sets the value of this to be the DOM element (not a jQuery-wrapped element) that actually triggered the event.

var validation = $("[data-validation]");
var validate;

validation.on("change keyup", function (e) {
  let validated = true;
  let value = this.value;
  validate = $(this).data("validation");

  if (value && value.trim() != "") {
    validated = false;
  } else {
    validated = true;
    return false;
  }

  if (validated) {
    $("[data-validator=" + validate + "]").prop("disabled", true);
  } else {
    $("[data-validator=" + validate + "]").prop("disabled", false);
  }
});
Related