jquerydynamictwitter-bootstrap-3alertinsertafter

Content not showing up in dynamic boostrap alert


I'm trying to create a dynamic bootstrap alert. However, the messages 'successfully saved' and 'failed' are not getting displayed.

When, I inspected and checked the html, I couldn't see the 'strong' tag iself getting added after 'a.close'.

What's wrong with the code?

$(document).ready(function(){
  $('.alert').hide();
  $('#success').click(function(){
	$('.message').text('');
	$('.message').removeClass('alert-danger');
	$('.message').addClass('alert-success');
	$('.alert-success').find('.close').after('<strong>Success: Successfully saved!');				
	$('.alert-success').show();
  });
					 
  $('#failure').click(function(){
	$('.message').text('');
	$('.message').removeClass('alert-success');
	$('.message').addClass('alert-danger');
	$('.alert-danger').find('.close').after('<strong>Failed!</strong>');
	$('.alert-danger').show();
  });
  setTimeout(function() { $(".message").fadeOut('slow'); }, 3000);	
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <div class="alert message">
	<a href="#" class="close" data-dismiss="alert" aria-label="close">X</a>
  </div>
</div>
<button id="success">Success</button>
<button id="failure">Failure</button>


Solution

  • Please update function as below.

    $('#success').click(function(){
        //$('.message').text('');
        $('.message').removeClass('alert-info');
        $('.message').addClass('alert-success');
        alert($('.alert-success').find('.close').html());
        $('.alert-success').find('.close').after('<strong>Success: Successfully saved!');               
        $('.alert-success').show();
      });
    

    Here i have put comment on $('.message').text(''); because this method text('') will clear a anchor tag as well.

    Here you also need to remove old class and old messages.