Matt
Matt

Reputation: 2213

Closing bootstrap alert with jQuery not working with this code?

I have this div:

<div class="alert alert-danger alert-dismissible" role="alert" id="login-error">
    <button type="button" class="close" id="close"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    Incorrect username or password.
</div>

which is hidden on page load with this:

$(document).ready(function(){
$('#login-error').hide();
});

I want to hide it when the user clicks the close button contained within the alert (it's shown when incorrect login details are supplied using .show();).

To do that I have this code from another Stackoverflow post:

$('.alert .close').on('click', function(e) {
$(this).parent().hide();
});

However, clicking the close button does not hide it and I have no idea why. If anyone could explain to me why it doesn't work so I can fix it that would be great :) Thanks.

Upvotes: 0

Views: 499

Answers (2)

jme11
jme11

Reputation: 17374

Well, in this case, the answer is simple. You don't have jQuery loaded.

Check out the errors in the console:

enter image description here

Also, once you load jQuery before your bootstrap.js file as required, you don't need to write your own script to handle closing the alert. Instead, you can just include the data-dismiss markup as described in the doc here:

Just add data-dismiss="alert" to your close button to automatically give an alert close functionality.

Upvotes: 1

Macbernie
Macbernie

Reputation: 1323

what about

$('#close').on('click', function(e) {
    $('#login-error').hide();
});

or

$("#close").click(function() {
    $('#login-error').hide();
});

Upvotes: 0

Related Questions