0

I have a code loop that adds options to a popup modal, with buttons alongside each option.

In a search loop, sometimes when the search returns multiple items, we must show the modal, and the user selects which part.

I want to pause the loop and wait for the user to choose an item, before continuing.

MY LOOP

$.each(rows, function (index, item) {
    SearchItems(item.split('\t')[0], item.split('\t')[1]);
});

SEARCH ITEM FUNCTION

function SearchItems(searchedPart, quantity) {

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "OrderFormServices.asmx/GetItemInfoAdmin",
        data: "{'itemname':'" + searchedPart + "','quantity':'" + (quantity || 1) + "', 'guid':'" + custGuid + "' }",
        dataType: "json",
        success: function (result) {

            result = result.d;

            if (result.length > 1) {

                var htmlString = "";
                $.each(result, function(index, item) {
                    item.PartNumber = (item.PartNumber != "") ? item.PartNumber : item.ItemName;
                    htmlString += "<tr><td>"
                        + "<input type=\"hidden\" name=\"ItemID\" value=\"" + item.ItemID + "\">"
                        + "<input type=\"hidden\" name=\"ItemCode\" value=\"" + item.ItemCode + "\">"
                        + "<input type=\"hidden\" name=\"Price\" value=\"" + item.Price + "\">"
                        + "<input type=\"hidden\" name=\"Quantity\" value=\"" + item.Quantity + "\">"
                        + "<input type=\"hidden\" name=\"CustomerReference\" value=\"" + searchedPart + "\">"
                        + "<input type=\"hidden\" name=\"PackQuantity\" value=\"" + item.PackQuantity + "\">"
                        + "<input type=\"hidden\" name=\"FreeStock\" value=\"" + item.FreeStock + "\">"
                        + item.PartNumber + "</td><td>"
                        + item.ManufacturerName + "</td><td>"
                        + item.ItemName + "</td><td>"
                        + item.ItemDescription + "</td><td><input type='button' name=\"selectPopup\" onclick=\"ChoosePopup($(this).closest('tr'));\" class='btn  btn-primary btn-xs' value='Select'></td></tr>";
                });
                $("#tbodyPopupContent").html(htmlString);
                $("#PopUpNormalProduct").modal();
                modalfix();
                $("#divPopupWindow").parent("").addClass("quicksearchpopup");

//////////////////////////////////////////////////////////////////////////
//////////////// WAIT FOR BUTTON CLICK AND PERFORM CODE///////////////////
//////////////////////////////////////////////////////////////////////////

                $("#partNumber").prop("disabled", false);

            } else if (result.length < 1) {
                $("#partNumber").prop("disabled", false);
                $('#partNumber').focus();
            }
            else {
                ///////
            }
        }
    });
}

The popup item buttons fire a ChoosePopup() function.

function ChoosePopup(row) {

    var $hidden_fields = row.find("input:hidden");
    var $tds = row.find("td");

    var newItem = {
        ItemID: parseFloat($hidden_fields.eq(0).val()),
        ItemCode: $hidden_fields.eq(1).val(),
        ItemDescription: $tds.eq(3).text(),
        ItemName: $tds.eq(2).text(),
        Price: parseFloat($hidden_fields.eq(2).val()),
        Quantity: parseFloat($hidden_fields.eq(3).val()),
        CustomerReference: $hidden_fields.eq(4).val(),
        PackQuantity: parseFloat($hidden_fields.eq(5).val()),
        FreeStock: parseFloat($hidden_fields.eq(6).val())
    };

    AddNewRow(newItem, true);
    $("#PopUpNormalProduct").modal("hide");
}

How can I wait for this ChoosePopup() function to complete, before continuing the loop?

1
  • 1
    alert('click to continue');? Commented Feb 14, 2017 at 4:16

2 Answers 2

1

I think you should re-think the way you are approaching the problem. You should fire your ChoosePopup function with a callback to do the rest of the work based on the user input.

You might consider passing the rows array into the SearchItems function, so that you can setup your callback to iterate through the remaining items in rows.

Here's an example that doesn't require duplicated code.

const items = [1, 2, 3, 4, 5]

//main function which writes buttons from an array
function makeButtons(array) {
  //copy the array so we can keep track of which items are left to process after click event
  var unProcItems = array.slice()
  $.each(array, function(index, item) {

    var exit = false
      //remove the item from the processed array
    unProcItems.splice(unProcItems.indexOf(item), 1)

    //make our button
    var button = document.createElement('button')
    button.innerHTML = `Button ${item}`

    //if something then hook up a click event with callback
    if (item == 3) {
      button.onclick = function(event) {
        //call our makeButtons function in the callback passing in the unprocessed items array
        makeButtons(unProcItems)

        //remove the click event so it can't be fired again
        event.target.onclick = null
      }
      exit = true
    }
    document.getElementById('content').append(button)

    //exit the loop if our flag was set
    if (exit)
      return false;

  })
}

makeButtons(items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">

</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your input Jono, appreciate it :) Any chance you might be able to give me a bit of help with the callback function?
Sure thing, @BrendanGooden, have updated my answer to include some example code. Hope it helps :)
0

Define global variables and based on what the pop up asks for, move the rest of your code to ChoosePopup() Function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.