Andy Williams
Andy Williams

Reputation: 907

Cascading Dropdown using JQuery/AJAX return undefined results even though I can see the array

I have a JQuery Script that has an event listener added to a dropdown. I am also making an AJAX call to a handler. I am trying to populate another dropdown that is returned from the getJSON call.

    <script>
        $(function () {
            debugger;
        $("#bid").on("change", function () {
            var budgetId = $(this).val();
            $("#SuiteId").empty();
            $("#SuiteId").append("<option value=''>--- Select Suite Number ---</option>");
            $.getJSON(`?handler=SuiteId&budgetId=${budgetId}`, (data) => {
                $.each(data, function (i,item) {
                    $("#SuiteId").append(`<option value="${item.suiteId}">${item.suiteNo}</option>`);
                    return (i !== "result")
                });
            });
        });
    });
    </script>
}

The problem I have is with how my data is returning. For example: item = Array(3)

Here are the contents of my array

{suiteId: 123 suiteNo: "001"}
{suiteId: 456 suiteNo: "002"}
{suiteId: 789 suiteNo: "003"}

Instead my append method returns "undefined". Can anyone offer advice? Am i appending incorrectly? I'd like it to display based on the apprend method I have below.

Additional Note Removing .suiteId and .suiteNo yields my dropdown results like this

--- Select Suite Number ---
[object Object],[object Object],[object Object]

Upvotes: 0

Views: 214

Answers (1)

ikiK
ikiK

Reputation: 6532

When you remove .suiteId from item and you get [object Object],[object Object],[object Object] in option it means your item is still an array and you are not looping your data correctly, and is also reason behind undefined.

Because you did not post your exact data format you are getting as response in order for us to see exact structure you can as fast fix add another loop:

$.each(data, function(i, item) {
  item.forEach(opt => {
    $("#SuiteId").append(`<option value="${opt.suiteId}">${opt.suiteNo}</option>`);
    return (i !== "result")
  })
});

and once again I am saying you have one for each to many, you need just one, but we need to see exact output not just contents of data.

Upvotes: 1

Related Questions