nas
nas

Reputation: 2437

How to pass parameters to the jquery alert function

I have html table with a delete button. I want to delete the row on button click. For this purpose, when I click a button with class '.btn-danger' which will open a JQuery alert window. My problem is how to pass the $(this) of button click to the $.alert Yes function, so I can remove that row. I have my code below.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>

$(document).ready(function() {
    $('.btn-danger').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        var id = $(this).closest('tr').attr('id');
        $.alert({
            title: 'Alert!',
            content: 'Are you sure you want to delete data?',
            buttons: {
                Yes: function (me) {
                    //pass value
                },
                No: function () {
                    //close function
                }
            }
        });
    });
});

Upvotes: 0

Views: 3177

Answers (2)

Ruslan Kolibabchuk
Ruslan Kolibabchuk

Reputation: 177

You can try something like this code (If I correct understand you issue)

$(document).ready(function() {
    $('.btn-danger').on('click', function(e){
        e.preventDefault();
        var me = $(this);
        $.alert({
            title: 'Alert!',
            content: 'Are you sure you want to delete data?',
            buttons: {
                Yes: function () {
                    me.closest('tr').remove();
                },
                No: function () {
                    //close function
                }
            }
        });
    });
});

jsfiddle example

Upvotes: 1

Remove me from Yes: function (me) {} because you have already declared it. Then you can call it like below.

Yes: function() {
    console.log(me)
},

$('.btn-danger').on('click', function(e) {
  e.preventDefault();
  var me = $(this);
  var id = $(this).closest('tr').attr('id');
  $.alert({
    title: 'Alert!',
    content: 'Are you sure you want to delete data?',
    buttons: {
      Yes: function() {
        console.log(me)
        //$("tr#" + id).remove() <--- example of removing the row
      },
      No: function() {
        //close function
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.1.0/jquery-confirm.min.css" rel="stylesheet" />

<button class="btn btn-danger">delete</button>

Upvotes: 3

Related Questions