0

I have the following code to populate a drop-down box on a form. The code seems to work but it throws an error "cannot read property id of undefined".

jquery

function LoadAnnualCredits() {
    try {
        var $dropdown = $("#creditQty");
        $dropdown.empty();
        var arrayList = [
            { "Id": 5000, "Name": "5,000" },
            { "Id": 10000, "Name": "10,000" }
        ];
        for (var i = 0; i <= arrayList.length; i++) {
            $dropdown.append($("<option />").val(arrayList[i].Id).text(arrayList[i].Name));
        }
    }
    catch (err) {
        alert(err);
    }
}

Razor View Code

@Html.DropDownListFor(m => m.NumCredits, Model.CreditQty, "Choose Qty", new { @class = "form-control", @id = "creditQty", @style = "width: 160px; height: 36px; line-height: 36px; padding: 4px;", @onchange = "CreditQtyChanged(this.value);" })

I tried using forEach method. No error msg but for some strange reason, it gives me duplicate items in the drop-down list:

5,000

5,000

10,000

10,000

function LoadAnnualCredits() {
    try {
        var $dropdown = $("#creditQty");
        $dropdown.empty();
        let arrayList = [
            { "Id": 5000, "Name": "5,000" },
            { "Id": 10000, "Name": "10,000" }
        ];
        arrayList.forEach(function (e) {
            $dropdown.append($('<option><option/>').val(e.Id).text(e.Name));
        });
    }
    catch (err) {
        alert(err);
    }
}

1 Answer 1

2

Your error can be a condition of the FOR loop, where it is (i <= arrayList.length), change to that (i < arrayList.length), the variable "i" equals 0, so it does not find a position equal to 2, since its array has only two elements (goes to position 1). Arrays in Javascript start at 0, so your element of position 2 is not found, that's what you're doing. Just change the condition and this will solve the problem.

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

1 Comment

silly me. spent too long working on office interop project where indexing crazily starts at 1. i should have spotted that one. thanks Mateus :)

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.