Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add event listener for html buttons in sweetalert dialog box in jquery

I am using SweetAlert box and I have three buttons, which i created using html inputs but I need to have three different click event listener performing different actions on each button click but its not working. Please help

$('#btnProcessRequest').click(function (e) {
   e.preventDefault(); // 
   var btn = "button";

   swal({
         title: "HTML <small>Consultation Review</small>!",
         text:  '<button type="' + btn + '" id="btnA" >A</button> ' +
                '<button type="' + btn + '" id="btnB" >B</button> ' +
                '<button type="' + btn + '" id="btnC" >C</button>',
          html: true 

       }, function (idd) {

             $("#btnA").click(function () {
                    alert(this.id);
             });

             $("#btnB").click(function () {
                    alert(this.id);
             });

             $("#btnC").click(function () {
                    alert(this.id);
             });
      });
 });
like image 372
Mahrukh Mehmood Avatar asked Feb 08 '23 19:02

Mahrukh Mehmood


1 Answers

Buttons are created on run-time hence you will need event delegation

Note: If you attach events this ways, they will be attached every time sweet alert is invoked. Bind then out of swal initialization.

Try this:

$("#btnProcessRequest").click(function(e) {
  e.preventDefault();
  var btn = "button";
  swal({
    title: "HTML <small>Consultation Review</small>!",
    text: '<button type="' + btn + '" id="btnA" >A</button> ' +
      '<button type="' + btn + '" id="btnB" >B</button> ' +
      '<button type="' + btn + '" id="btnC" >C</button>',
    html: true,
    showConfirmButton: false
  });
});
$(document).on('click', "#btnA", function() {
  alert(this.id);
});

$(document).on('click', "#btnB", function() {
  alert(this.id);
});

$(document).on('click', "#btnC", function() {
  alert(this.id);
});
<script src="http://tristanedwards.me/u/SweetAlert/lib/sweet-alert.js"></script>
<link href="http://tristanedwards.me/u/SweetAlert/lib/sweet-alert.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="btnProcessRequest">
  Show Sweet Alert
</button>
like image 143
Rayon Avatar answered Feb 10 '23 23:02

Rayon