Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide bootstrap alert if empty don´t work

I want to hide my bootstrap alert if it is empty. It hide correctly when page load, problem is when I do a push who insert data into div, it don´t show alert and it keep with display = none

enter image description here

HTML

 <div id="a1" class="alert alert-success">
                <div id="discussion"></div>
            </div>

JS:

<script type="text/javascript">
    hideAlert("a1");

    function hideAlert(id) {
        var text = $('#' + id + '#discussion').text();
        console.log(text.length);
        if (text.length <= 0)
            $('#' + id).hide();
    }
</script>

Edit

I try it using input event , it occurs same. It hide but it don't show when get value

JS:

<script type="text/javascript">
    $('#discussion').keyup(function () {

        // If value is not empty
        if ($(this).val().length == 0) {
            // Hide the element
            $('#a1').hide();
        } else {
            // Otherwise show it
            $('#a1').show();
        }
    }).keyup();


</script>
like image 779
Ledwing Avatar asked Sep 15 '25 15:09

Ledwing


2 Answers

Your selector must be #a1 #discussion no #a1#discussion.So:

Change :

$('#' + id + '#discussion')

To:

$('#' + id + ' #discussion')
              ^-----------------

hideAlert("a1");
function hideAlert(id) {
    var text = $('#' + id + ' #discussion').text();
    console.log(text.length);
    if (text.length <= 0)
        $('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
    <div id="discussion"></div>
</div>

After Update your question:

setInterval(function(){ hideAlert("a1"); }, 3000);

function hideAlert(id) {
    var text = $('#' + id + ' #discussion').text();
    if (text.length <= 0)
    $('#' + id).hide();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="a1" class="alert alert-success">
    <div id="discussion" contenteditable="true">Some Text...</div>
</div>

Note : Remove text in div and see result

like image 175
Ehsan Avatar answered Sep 17 '25 06:09

Ehsan


Why not try using the :empty css pseudo-class like this:

CSS

#discussion{
    display: block;
}     
#discussion:empty{
    display: none;
}

HTML

<div id="discussion" class="alert alert-success"></div>

Note: The beginning and closing tags should be next to each other for the pseudo-class to work (like the beginning and closing div tags next to each other without any line breaks or space in the html shown above).

like image 38
Parthipan Natkunam Avatar answered Sep 17 '25 04:09

Parthipan Natkunam