1

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);
  }
});
0

1 Answer 1

1

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);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I actually did try removing the validation.each() but for some reason it didn't work. I must've messed up something else. Thank you for the explanation and the quick answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.