petworthnick
petworthnick

Reputation: 215

How do I pass a value into a sweetalert?

I have a series of items populated from a database. I want to put a sweetalert change status confirmation message on each. How do I pass their ID into a sweetalert confirmation message?

In the section, I have a function which I want to run if they confirm the message, and if they don't I don't want it to do anything. I have the following code at the bottom of the page which is triggered when a link is clicked. However, I need to pass the productID into the alert so that it can be called in the updateProducts function.

$(`.link`).click(function () {
    swal({
        title: "Are you sure?",
        text: "Are you sure you want to change the status?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((confirm) => {
        if (confirm) {
            updateProducts(productID);
        } else {
            swal("The status has not changed.");
        }
    });
})

Upvotes: 2

Views: 5404

Answers (2)

GMKHussain
GMKHussain

Reputation: 4719

See example is it what you want ?

function updateProducts(y) {
  alert(y);
}


function someFunc(x) {
    swal({
          title: x , // <-- Passed Value
          text: "Are you sure you want to change the status?",
          icon: "warning",
          buttons: true,
          dangerMode: true,
        })
        .then((confirm) => {
          if (confirm) {
            updateProducts(x); // <-- do your code
          } else {
            swal("The status has not changed.");
          }
        });
}


let str = "My Value";





$(`.link`).click(function () {
  someFunc(str); // <-- run this on click event.
})
.link { padding:30px; background: #40cc40; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js" integrity="sha512-AA1Bzp5Q0K1KanKKmvN/4d3IRKVlv9PYgwFPvm32nPO6QS8yH1HO7LbgB1pgiOxPtfeg5zEn2ba64MUcqJx6CA==" crossorigin="anonymous"></script>


<button class="link">Click Me</button>

Upvotes: 0

Shahnawaz Hossan
Shahnawaz Hossan

Reputation: 2720

Just store your productID in a variable and pass it through a function like this:

$(`.link`).click(function () {

    var productID = 'productID';
    
    swal({
        title: "Are you sure?",
        text: "Are you sure you want to change the status?",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    }).then((confirm) => {
        if (confirm) {
            updateProducts(productID);
        } else {
            swal("The status has not changed.");
        }
    });
})

Upvotes: 1

Related Questions