173901
173901

Reputation: 709

jquery if contains text

I am making a log-in/off button using asp MVC 5 I have it set up so that the Session["isLoggedIn"] will show a different text if someone is logged in or not.

Now i need to code the JQuery to add an href to the login pages or logout respectively.

This is my Jquery

<script type="text/javascript">
    $(document).ready(function () {
        if ($("#loginLogoff").text("sign out"))
            $("#loginLogoff").attr("href", "javascript:document.getElementById('logoutForm').submit()");
        else 
            $("#loginLogoff").attr("href", "/Home#login_popup");
    });
</script>

I can get it to change to the logout page upon load. However it doesn't ever fire the else statement I have tried different keywords, all to no avail

.val()
.text()
.html() 

html block looks like this in c#

<li style="padding-top:10px;text-align:right;"><strong>@Session["LoginStatus"]</strong> | <a id="loginLogoff" style="display:inline;"> @Session["logInOffToggle"]</a></li>

and in formatted html

<li style="padding-top:10px;text-align:right;"><strong>not Logged In</strong> | <a id="loginLogoff" style="display:inline;"> Login</a></li>

Upvotes: 0

Views: 226

Answers (1)

321hendrik
321hendrik

Reputation: 177

The Else-Block is never run, because the jQuery method .text("String") sets the text of the result list it is called upon and returns the same result list. So in your case this is always true, since a not empty list evalutes to true.

You want to use the .text() method without an argument to get the text.

You should change your condition like so:

if ( $("#loginLogoff").text() === "sign out" ) {
    ...
} 

Upvotes: 2

Related Questions