jqueryloopsdialog

Jquery dialog box inside each/for loop


I'm trying to choose what math operation do with each number of an array. I've tried with array.each() function and now with for() and to make the selection I've tried with confirm() plugin and now with jquery's dialog() function.

And as an asynchronus tool, it doesn't wait for my selection and it jumps outside the loop inmediatly. How can I add a script stopper and wait for my response?

Thanks a lot!! And have a good day

My code is this:

var result = 0;
      const items = [1, 2, 3, 4, 5];
      for (const item of items) {
        console.log("item=",item);
        var message_alert = $("<p>Ya existe la acción "+item+" en el centro "+item+".</p>").dialog({
          buttons: {
            add: function () {
                alert('add!');
                result += item;
                console.log("result=",result);
            },
            multiply: function () {
                alert('multiply!');
                result *= item;
                console.log("result=",result);
            },
            cancel: function () {
                alert('ignore!');
                console.log("result=",result);
            }
          }
       });

Solution

  • You need to use async/await with Promises to "pause" the loop until a dialog button is clicked.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Async Dialog Example</title>
      <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
      <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    </head>
    <body>
    
    <div id="dialog" style="display:none;"></div>
    
    <script>
    async function askUserAction(item) {
      return new Promise((resolve) => {
        $("#dialog").html(`<p>Choose operation for item ${item}:</p>`).dialog({
          modal: true,
          buttons: {
            Add: function () {
              $(this).dialog("close");
              resolve("add");
            },
            Multiply: function () {
              $(this).dialog("close");
              resolve("multiply");
            },
            Cancel: function () {
              $(this).dialog("close");
              resolve("cancel");
            }
          }
        });
      });
    }
    
    async function processItems() {
      let result = 0;
      const items = [1, 2, 3, 4, 5];
    
      for (const item of items) {
        console.log("Processing item:", item);
        const action = await askUserAction(item);
    
        if (action === "add") {
          result += item;
        } else if (action === "multiply") {
          result *= item;
        } // cancel does nothing
    
        console.log("Current result:", result);
      }
    
      alert("Final result: " + result);
    }
    
    processItems();
    </script>
    
    </body>
    </html>