I'm trying to create a default response using alerts do bootstrap
my goal with a simple:
$(".alert").addClass('alert-success').text('Configurações salvas com sucesso.');
I choose the class alert-success
and enter a text in the alert.
When in the same button click and in this should show a warning
because the person did not fill a field for example I use:
$(".alert").addClass('alert-warning').text('Selecione um Banco/Empresa Por favor.');
The 1st problem comes because the class alert-success
is already inserted in the gift
and in that case I need to remove it like this:
if($(".alert").hasClass('alert-success')){ $(this).removeClass('alert-success'); }
Verify that the class exists and remove.
So every time I'm going to add a new message I have to check if the class exists to remove it.
and by using close
of alert
it uses an attribute called data-dismiss
that completely removes the element. I used the hide()
method.
Would there be any way to simplify this whole process of alerts?
$("#success").click(function() {
if ($(".alert").hasClass('btn-warning')) {
$(".alert").removeClass('btn-warning');
}
$(".alert").toggle().addClass('btn-success');
$(".alert #resposta").text("This is a Success message!");
});
$("#warning").click(function() {
$(".alert #resposta").text("This is a Warning message!");
if ($(".alert").hasClass('btn-success')) {
$(this).removeClass('btn-success');
}
$(".alert").toggle().addClass('btn-warning');
});
$("[data-hide]").on("click", function() {
$("." + $(this).attr("data-hide")).hide();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button class='btn btn-success' id='success'>success</button>
<br>
<br>
<button class='btn btn-warning' id='warning'>warning</button>
<br>
<br>
<div class="alert text-center" role="alert">
<a href="#" class="close" data-hide="alert">×</a>
<div id="resposta"></div>
</div>