I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
    <li><a href="index.php">Home</a>  <span class="divider">/</span> </li>
    <li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']);  ?> </li>
</ul>
Javascript
$(document).ready(function () {
    var testRole = $("#activeUser").text();
    //This block of code works
    role = 'Guest';
    if (role == 'Guest') {
        alert("Inside if");
        $("#request_history_li").hide();
        $("#assign_role_li").hide();
        $("#volunteer_li").hide();
        $("#profile_li").show();
        $("#change_password_li").show();
    }
    //This doesn't work why?
    if (testRole == 'Guest') {
        alert("Inside if");
        $("#request_history_li").hide();
        $("#assign_role_li").hide();
        $("#volunteer_li").hide();
        $("#profile_li").show();
        $("#change_password_li").show();
    }
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.
The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution: You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if  you get spaces after < or before >, then these are white spaces, that are spoiling your party.
Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With