Home » Jquery » jquery – Using removeClass to adjust css on div not working

jquery – Using removeClass to adjust css on div not working

Posted by: admin February 22, 2020 Leave a comment


I am passing the value from a dropdwon to then show and hide a seperate div and to also add/remove a class to the same element. The show/hide works fine but the new class added (mine) is added but not removed.

Does anyone know how to remove the class when div is hidden, using code below?

            var optionValue = $(this).attr("value");
                $(".details-tcs").not("." + optionValue).hide();
                $("." + optionValue).show();
                $("." + optionValue).addClass("mine");

            } else{

Here is what I get when I change the dropdown around.

<div class="details-tcs SC mine" style="display: none;">
<div class="details-tcs AI mine" style="display: block;">
<div class="details-tcs BB mine" style="display: none;">

It leaves the ‘mine’ showing once added.

The dropdown value is either SC, or AI or BB from –

How to&Answer:

The attribute value is not updated on an element when its value changes; it serves only as initial value. That means if your select elements are initially empty, $(this).attr("value"); gets you "" (an empty string). When coerced to a Boolean, as in if (optionValue), an empty string is evaluated to false. If it does have an initial value, that attribute is never going to change, so $(this).attr("value"); will always return a non-empty string, which, when coerced to a Boolean as in if (optionValue), evaluates to true.

You are probably looking for the property value instead:

var optionValue = $(this).prop("value");