简体   繁体   中英

jQuery addClass and removeClass in if else statement not working

So I have created a class with a border. called border-check. This border only needs to show when the td.k-editable-area has no value (nothing written in the textarea).

I can add a class with the first line but once I add the if else statement it breaks down and wont add the class. So I'm not sure if its a problem of adding the class again or wether my if else statement is not correctly stated.

$("td.k-editable-area").addClass("border-check");

if ("td.k-editable-area" == "") {
    $("td.k-editable-area").addClass("border-check");
} else {
    $("td.k-editable-area").removeClass("border-check");
}

Your if statement is comparing two different strings.

"td.k-editable-area" == "" //false

It is not taking value from the element $("td.k-editable-area") , so make it

if ( $("td.k-editable-area").text().trim() == "") {

Edit

If this has to be checked for multiple td s then

$("td.k-editable-area").each( function(){
   var $this = $(this);
   if ( $this.text().trim() == "") {
      $this.addClass("border-check");
   } else {
      $this.removeClass("border-check");
   }
})

As the others have said, your condition is testing two strings, which isn't what you want.

If your goal is to add/remove the class on each of those td s based on whether that specific one is empty, you'll need a loop:

$("td.k-editable-area").each(function() {
    var $this = $(this);
    $this.toggleClass("border-check", !$this.text().trim());
});

You can't just use

// NOT THIS
$("td.k-editable-area").toggleClass("border-check", !$("td.k-editable-area").text().trim());

...because that will update the class on all elements based on whether they're all blank. (With any other jQuery accessor, it would be based on the first one, but text is weird.)

OP here, I have ended up finding the answer with your help. Thanks you! The correct code was:

 function onEditorChange(e) {
            var text = e.sender.body.innerText;

            if (text.trim() === "") {
                $("td.k-editable-area").addClass("border-check");
            } else {
                $("td.k-editable-area").removeClass("border-check");
            } 
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM