简体   繁体   中英

how to use bootstrap alert message inside a javascript function?

I would like to add Bootstrap alert messages inside the JavaScript function.

Eg:

<div class="alert alert-success fade in">
     <a href="#" class="close" data-dismiss="alert">&times;</a>
     <strong>Success!</strong> Your message has been sent successfully.
</div>

The above div content displays a success message. I want to call this inside my JavaScript code, if my web service returns a success message.

You can set toggle your web service returns. This example working with click function.

 function toggleAlert(){ $(".alert").toggleClass('in out'); return false; // Keep close.bs.alert event from removing from DOM } $("#btn").on("click", toggleAlert); $('#bsalert').on('close.bs.alert', toggleAlert) 
 <link rel="stylesheet" type="text/css" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <button id="btn">Toggle</button> <div class="alert alert-info fade out" id="bsalert"> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <strong>Info!</strong> This alert box could indicate a neutral informative or action </div> <div> content 

Create a class to initially hide the alert

.hide{
  display:none
}

<div id = "alertId" class="alert alert-success fade in hide">
       //rest of code
</div>

In js in the success function

 document.getElementById('alertId').classList.remove('hide')

 $("#success-alert").hide(); $("#test").click(function showAlert() { $("#success-alert").fadeTo(2000, 500).slideUp(500, function(){ $("#success-alert").slideUp(500); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.1.1/css/bootstrap.min.css"> <div> <button id="test">Result</button> </div> <div class="alert alert-success" id="success-alert"> <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>Success!</strong> Your message has been sent successfully. </div> 

You can use the above snippet code, but place the code in button .click() event after the return of the server result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM