简体   繁体   中英

How to close BootStrap alert automatically?

<div class="col-sm-6 form-box">
    <div class ="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert"> <i class="fa fa-times-circle-o"></i> </button>             
           <?php
                foreach ($_SESSION['error'] as $e) {
                    echo $e;
                }
                unset($_SESSION['error']);
           ?>   
    </div>
</div> 

This is the code that I have to print out errors using bootstrap alert, But however the alert box stays on the screen even when there is no errors (after refreshing the page).

I have tried to do it using JavaScript but it doesn't seems to work. Can someone help me to fix this problem. So that the error alert only pops up when there is an error from $_SESSION['error] .

Thanks

There are a couple ways.

1) If you want to totally exclude the alert if there are no errors:

<?php if(isset($_SESSION['error']) AND ! empty($_SESSION['error'])): ?>
<div class="col-sm-6 form-box">
        <div class ="alert alert-danger alert-dismissable">
            <button type="button" class="close" data-dismiss="alert"> <i class="fa fa-times-circle-o"></i> </button>  

           <?php
                foreach ($_SESSION['error'] as $e){
                                    echo $e;
                }
                unset($_SESSION['error']);
           ?>   
        </div>
</div> 
<?php endif; ?>

2) Just hide the alert but keep it on the page. Then you could hide or show it with JS later:

<?php $showAlert = (isset($_SESSION['error']) AND ! empty($_SESSION['error'])) ? '' :'style="display:none;'; ?>
<div class="col-sm-6 form-box">
        <div class ="alert alert-danger alert-dismissable" <?= $showAlert; ?> >
            <button type="button" class="close" data-dismiss="alert"> <i class="fa fa-times-circle-o"></i> </button>  

           <?php
                foreach ($_SESSION['error'] as $e){
                                    echo $e;
                }
                unset($_SESSION['error']);
           ?>   
        </div>
</div> 

Just a couple options, these could be done better.

You can also hide the alert with jQuery:

$('.alert').hide(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM