OneMoreQuestion OneMoreQuestion - 4 months ago 18
Javascript Question

How to hide Bootstrap alert box when no message

I made a simple alert box with Bootstrap like this

<div class="alertBox">
<span role="alert" class="alert alert-info"> bag.session.username </span>
</div>


When there is no alert (box is empty), the box still shows on the page like this. enter image description here

So I tried to hide it when it's empty with like so:

<script type="text/javascript">
$(document).ready(function () {
if (bag.session.username) {
$(".alertBox").show();
}
else {
$(".alertBox").hide();
}
});
</script>


This basically says if an alert message is there, show the box, if not, hide it. However, this does not work as expected. The box is there until there is no alert. How can I solve this?

Answer

Make sure to initially hide your alert box. Also it looks like your putting a JavaScript variable right into your HTML. Also the string bag.session.username may always evaluate to true. Maybe this?

<script type="text/javascript">
$(document).ready(function () {
    if (typeof bag.session.username != "undefined") {
        $(".alertBox span").text(bag.session.username);
        $(".alertBox").show();
    }
    else {
        $(".alertBox").hide();
    }
});
</script>