Draco
Draco

Reputation: 16354

addClass function not worked using JQuery

I have the following code:

function showAccessRequests_click() {
    var buttonValue = $("#showAccessRequests").val();
    if (buttonValue == "Show") {
        $(".hideAccessRequest").removeClass("hideAccessRequest");
        $("#showAccessRequests").val("Hide");
    }
    else {
        $(".hideAccessRequest").addClass("hideAccessRequest");
        $("#showAccessRequests").val("Show");
    }
}

This script removes a class fine but it does not want to add the class. Can you see any issues with this code?

Upvotes: 1

Views: 3972

Answers (3)

Tracker1
Tracker1

Reputation: 19344

you'd need an identifier for the classes you want to toggle ex:"accessRequest"... try this.

function showAccessRequests_click() {
    var buttonValue = $("#showAccessRequests").val();
    if (buttonValue == "Show") {
        $(".accessRequest").removeClass("hideAccessRequest");
        $("#showAccessRequests").val("Hide");
    }
    else {
        $(".accessRequest").addClass("hideAccessRequest");
        $("#showAccessRequests").val("Show");
    }
}

classes are space-delimited, so if you want them hidden by default...

<div class="accessRequest hideAccessRequest">...</div>

Upvotes: 0

meandmycode
meandmycode

Reputation: 17317

When you add hideAccessRequest class to the element, you search for it by the existence of that class.. if you are adding it, that class won't already be applied and thus you won't match any elements.

Upvotes: 6

SilentGhost
SilentGhost

Reputation: 319601

$(".hideAccessRequest") doesn't exist. you need to use id, I guess. And you might want to look at toggleClass.

Upvotes: 1

Related Questions