2

HTML:

<!-- try to change the value="" -->
<input class="test" type="text" value="">

jQuery

$(function () {

        if (!$(".test").val()) {
        alert("Empty");
            $(this).addClass("removeMe");
        } else {
        alert("not Empty");
            $(this).addClass("addMe");
        }

});

Why $(this) doesn't work here? And what is it possible to do about it if, say there's more than one element(.test) to include, for example 3: if (!$(".test, .test2, .test3").val()) {

sorvz
  • 123
  • 7

1 Answers1

4

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() && ... ) {
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303