4
I’m trying to create a standard response using the 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 insert a text into Alert.
When on the same button I click and it 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 1° problem comes, because the class alert-success
already inserted in the gift
and in that case I need to remove it so:
if($(".alert").hasClass('alert-success')){ $(this).removeClass('alert-success'); }
I check if the class exists and remove.
So every time I add a new message I have to check if there is a class to remove it.
and for using the close
of alert
it uses an attribute called data-dismiss
that completely removes the element. inves used the method hide()
.
Would there be some way to simplify this whole Alerts process ?
$("#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>
<script src="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>