最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Adding Cancel Button to Javascript Alert - Stack Overflow

programmeradmin3浏览0评论

Here is my Javascript Alert:

<script>
function showMessage() {
    setTimeout(function() {
alert("alert");
}, 100);
}
</script>

When a user visits a page, a window pops up that says "alert" and it only has the "Ok" button. When it is clicked, the window goes away and displays the page under it. How do I add a "Cancel" button that has the same effect?

Here is my Javascript Alert:

<script>
function showMessage() {
    setTimeout(function() {
alert("alert");
}, 100);
}
</script>

When a user visits a page, a window pops up that says "alert" and it only has the "Ok" button. When it is clicked, the window goes away and displays the page under it. How do I add a "Cancel" button that has the same effect?

Share Improve this question edited Jul 21, 2020 at 13:05 Tanjim Ahmed Khan 6961 gold badge9 silver badges22 bronze badges asked Oct 9, 2014 at 15:00 Joe BobbyJoe Bobby 2,81111 gold badges43 silver badges63 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 15

Well you can use window.confirm

confirm("alert");

The above returns true or false based on the selection.

There are three types of dialog boxes in JavaScript, (correct me if i'm wrong on this)

  1. OK
  2. OK and Cancel
  3. Input/prompt.
    These JavaScript boxes cannot be customized.
    If you want a customized dialog box I suggest jqueryui.com

you can use the confirm() to provide the cancel button. below is a simple example to use Cancel button

  <!DOCTYPE html>
    <html>
    <body>
    
    
        <div style="text-align: center;" xss=removed>
    <button  onclick="myFunction()"  >click Me</button>
    <div></div>
    
    <script>
    function myFunction() {
      confirm("Press a button!");
    }
    </script>
    
    </body>
    </html>
    

Instead of using alert you need to use confirm for showing pop-up and based on the input to that pop-up you can tack your own action.

here i provide you a code snippet for the same

<html>
<body>
<button onclick="showAlert()">Click Me!</button>
<p id="onOkClick" style="display:none">Ok</p>
<p id="onCancleClick" style="display:none">Cancle</p>
<script>
  function showAlert()
  {
    if(confirm("Hello I am Alert !"))
    {
   document.getElementById("onOkClick").style.display="block";
         document.getElementById("onCancleClick").style.display="none"
}
    else
    {
   document.getElementById("onOkClick").style.display="none";
         document.getElementById("onCancleClick").style.display="block"
}
  }
</script>
</body>
</html>

发布评论

评论列表(0)

  1. 暂无评论