Multiple Bootstrap Alerts

Asked

Viewed 3,696 times

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().

Alert Message

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">&times;</a>
  <div id="resposta"></div>
</div>

4 answers

3


I was able to solve this question by creating a function that receives the example alert sucesso,atencao,erro and the texto and give a append in a div I created ex: resposta, the function is in charge of eliminating the alert in the click and also in the close, and in the alternation of alerts I can clear the alert using empty():

   function msg(alerta, texto) {
     var resposta = '';
     $("#resposta").empty();
     if (alerta === 'sucesso') {
       resposta = "<div class='alert btn-success text-center' role='alert'>" +
         "<a href='#' class='close' data-dismiss='alert' aria-label='Close'>&times;</a>" +
         texto + "</div>";
     } else if (alerta === 'atencao') {
       resposta = "<div class='alert btn-warning text-center' role='alert'>" +
         "<a href='#' class='close' data-dismiss='alert' aria-label='Close'>&times;</a>" +
         texto + "</div>";
     } else if (alerta === 'erro') {
       resposta = "<div class='alert btn-danger text-center' role='alert'>" +
         "<a href='#' class='close' data-dismiss='alert' aria-label='Close'>&times;</a>" +
         texto + "</div>";
     }
     $("#resposta").append(resposta);

     $(".alert").click(function() {
       $(".alert").hide();
     });
   }

   $("#success").click(function() {
     msg('sucesso', 'Configuracoes salvas com sucesso.');
   });

   $("#warning").click(function() {
     msg('atencao', 'Preencha o campo XXXX por favor.');
   });
   $("#danger").click(function() {
     msg('erro', 'Error Tem alguma coisa errada que nao esta certa.');
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<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>
<br>
<br>
<div class="col-xs-4">
  <button class='btn btn-success btn-block' id='success'>success</button>
</div>
<div class="col-xs-4">
  <button class='btn btn-warning btn-block' id='warning'>warning</button>
</div>
<div class="col-xs-4">
  <button class='btn btn-danger btn-block' id='danger'>danger</button>
</div>
<br>
<br>
<br>
<div id="resposta"></div>

2

Surely there’s... there’s n possible ways, but based on your example, you can simply do so:

function setTextInAlert(classe, message) {
    $('.alert').attr('class', classe);
    $('#resposta').text(message);
}

$(document).ready(function(){

   $('.botao').on('click', function(){

      var id = $(this).attr('id');

       switch(id) {
        case 'msg_01':
          setTextInAlert('alert btn-success text-center', 'Message Success!');
         break;
        case 'msg_02':
          setTextInAlert('alert btn-warning text-center', 'Message Warning!');
         break;
        case 'msg_03':
          setTextInAlert('alert btn-danger text-center', 'Message Danger!');
         break;
       }

   });
});

And in your html:


<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 botao' id="msg_01">success</button>
<br>
<br>
<button class='btn btn-warning botao' id="msg_02">warning</button>
<br>
<br>
<button class='btn btn-danger botao'  id="msg_03">error</button>

<div class="alert text-center" role="alert">
  <a href="#" class="close" data-hide="alert">×</a>
  <div id="resposta"></div>
</div>

2

I also had this same problem when implementing these messages on my system. However I decided by applying the $(this) before its closure.

$("#success-alert").fadeTo(3000, 500).slideUp(500, function () {
      $(this).find("#success-alert").alert('close');
 });

0

I know it’s not a direct answer, but I’ve been very successful in using Bootbox.js.

It is quite useful in cases like this, where you want a similar message to appear alert() but want to use the bootstrap style. bootbox.js is super-easy to use, although I haven’t found any documentation in English.

The biggest advantage is because you don’t need any HTML - create everything whenever you need it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.