Search code examples
javascriptswitch-statementdynamic-arrayssweetalert

Making a sweet alert with a dynamic amount of choices


I am using sweet alert in a project for the user to make choices. Then after a choice is made, I execute my code using switch statement inside of .then. So for instance, say we need to have the user select a confirm option or a cancel option. I know how to do this:

swal( 'Are you sure you want to do this thing?', {
    buttons: {
        no: {
            text: "No",
            value: "cancel",
        },
        yes: {
            text: "Yes",
            value: "confirm",
        },
    },
  })
  .then ( (value) => {
    switch (value) {
    case 'confirm':
    // do the confirm stuff here
    break;

    case 'cancel':
    // do the cancel stuff here
    break;
    }
  });

Now I run into a problem. I have an array that is dynamically filled with choices, say

let choices = [];

and at earlier parts in the project, different strings can be pushed to this array. My question is, how do I adjust my sweet alert code above to account for an arbitrary amount of choices and then executing the switch code for them?


Solution

  • Well I have found a solution, and I have done it using HTML select tag and then injecting that into sweet alert using customizable content:

    let choices = document.createElement("select");
      let names = ['nameOne', 'nameTwo', 'nameThree'];
      names.forEach(name => {
        let opt = document.createElement("option");
        opt.appendChild(document.createTextNode(name));
        opt.value = name;
        choices.appendChild(opt);
      });
      swal('Testing', 'Choose an item', { content: choices })
    .then( () => {
      for (let item of choices) {
        if (item.selected == true) {
           // do stuff
        }
       }
     });
    

    Note that this will work for any arbitrarily long array of objects, since we use the forEach function to loop through all items in the array and make an option out of them.