Reputation: 1532
I'm creating a form where an error message appears when the input loses focus if the input is empty. I also want to add a class to the input to give it a red border.
The problem arises when I add $(this).addClass("error");
- the error message no longer shows. Does using addClass()
change the reference of this
within the function? Can anybody explain to me what is happening? I'm usually pretty good with jQuery but I'm a bit lost here.
Here's my code:
$(function() {
$.fn.showError = function(error) {
$(this).addClass("error");
$errorElement = this.closest(".input-field").find(".error");
if (!$errorElement.length) {
$errorElement = $('<span class="error"></span>').appendTo(this.closest(".input-field"));
}
$errorElement.text(this.data("errormsg"));
};
$("input").on("focusout", function(e) {
$(this).showError();
});
});
.error {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="input-field">
<input type="text" data-errormsg="Please enter your first name" />
</div>
Upvotes: 1
Views: 113
Reputation: 14269
$errorElement = this.closest(".input-field").find(".error");
Since you just added error
to the input, this line finds the input and adds the text to it, however since an input element has no children, the text isn't shown. Use
$errorElement = this.closest(".input-field").find("span.error");
Upvotes: 2