-1

HTML:

<input class="test removeMe" type="text">

jQuery:

$(function () {
    function isEmpty() {
        if (!$(".test").val()) {
            $(this).removeClass("removeMe");
        } else {
            $(this).addClass("addMe");
        }
    }
    isEmpty();
});

Please, tell me, where am I wrong?

I want isEmpty to fire on load/reload and check if the input has value. If it doesn't, it will remove the removeMe class. If it does have some value, it will add addMe class to it.

Console is empty, I can't figure it out why this isn't working properly.

Update:

Very odd... It does fire proper alert relatively if it is empty or not, but doesn't add/remove classes. https://jsfiddle.net/37tt3x72/1/

Update 02

It does work, but not exactly... https://jsfiddle.net/37tt3x72/2/ The this isn't working... if replace it with the targeted element, than it will work. So the question is remained: Why this isn't working here?

sorvz
  • 123
  • 7

3 Answers3

0

$(function () {
    function isEmpty() {
        if (!$(".test").val()) {
          alert("Empty");
            $(this).removeClass("removeMe");
        } else {       
         alert("not Empty");
            $(this).addClass("addMe");
        }
    }
    isEmpty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="test removeMe" type="text">
Sarika Koli
  • 763
  • 6
  • 11
  • I'm totally lost, lol :) How can that be... And btw: you missed the `;` after first `alert`. – sorvz Apr 06 '17 at 12:27
  • No, it is not :) Or at least I'm not so convenient about it :) Try to implement styles to it and you will see it doesn't work as intended... But it does fire the proper alert... I don't get it. https://jsfiddle.net/37tt3x72/ – sorvz Apr 06 '17 at 12:32
0

Call function from document on ready function.

function isEmpty() {
    if (!$(".test").val()) {
        $(this).removeClass("removeMe");
    } else {
        $(this).addClass("addMe");
    }
}

$(document).ready(function(){
  isEmpty();
});
T L Patel
  • 86
  • 5
0

Rory McCrossan provided with great and informative answer here: Why "$(this)" doesn't work in the following example

And adeneo pointed out on another SO question/answers about how this works: How does the "this" keyword work?

Community
  • 1
  • 1
sorvz
  • 123
  • 7