Why "$(this)" Doesn't Work In The Following Example
HTML: jQuery $(function () { if (!$('.test').val()) { alert('Empty');
Solution 1:
The problem is because the code runs directly within the document.ready handler and is therefore within the scope of the document
, hence this
refers to the document
.
To achieve what you require you would be best to cache a selector and use that again to add the required class, like this:
$(function () {
var $test = $('.test');
if (!$test.val()) {
console.log("Empty");
$test.addClass("removeMe");
} else {
console.log("not Empty");
$test.addClass("addMe");
}
});
What is it possible to do about it if, say there's more than one element to include, for example 3:
if (!$(".test, .test2, .test3").val()) {
In that case you'd need to test each element individually:
if (!$('.test1').val() && !$('.test2').val() && ... ) {
Post a Comment for "Why "$(this)" Doesn't Work In The Following Example"