rks rks - 6 months ago 19
HTML Question

How can I stop a Bootstrap alert from automatically disappearing?

I want my button to display an alert after its clicked and stay there until its closed.

On my webpage the alert flashes on the screen for a split second every time the button is pressed.

On my jsfiddle the alert appears until its closed but does not reappear when the button is clicked again.

http://jsfiddle.net/g1rnnr8r/108/

Any ideas?

html

<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="submit" class="btn btn-primary">Submit</button>
<div class="alert alert-dismissible alert-success">
<button type="button" class="close" data-dismiss="alert">&times;</button>
<strong>Completed!</strong> Form successfully submitted...
</div>
</div>
</div>


css

<style>
.alert {
display: none;
}
</style>


js

<script>
$(document).ready(function () {
$('button').click(function () {
$('.alert').show()
})
});
</script>

Answer

Try this: See DEMO

When you use data-dismiss="alert", it totally remove the alert div. So, you try like this.

<body>
    <button type="submit" class="btn btn-primary">Submit</button>
    <div class="alert alert-dismissible alert-success">
        <button type="button" class="close">&times;</button>
        <strong>Completed!</strong> Form successfully submitted...
    </div>
</body>

JS:

$(document).ready(function(){
    $('button').click(function(){
        $('.alert').show()
    }); 

    $('button').click(function(){
        $(this).parents('div').hide();
    }); 
});

CSS:

.alert{
    display: none;
}
Comments