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

Questions:

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?

$(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".details-tcs").not("." + optionValue).hide();
                $("." + optionValue).show();
                $("." + optionValue).addClass("mine");

            } else{
                $(".details-tcs").hide();
                $(".details-tcs").removeClass("mine");
            }
        });

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

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

It leaves the ‘mine’ showing once added.

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

jQuery("select").change(function()
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");