Binding values to HTML dropdownlist using JQuery with ASP.NET MVC WebAPI - Cannot read property '0' of undefined

14,888

If you are certain that the data object is correct (it would have to just be an array of strings) this should work:

success: function(data) {
   for (var i = 0; i < data.length; i++) {
       var option = $("<option/>");
       option.attr("value", data[i]).text(data[i]);
       testDdl.append(option);
    }
 },

Here is a fiddle of it in action: http://jsfiddle.net/aq8X5/5/

Share:
14,888
Uba
Author by

Uba

Updated on June 04, 2022

Comments

  • Uba
    Uba almost 2 years

    I am trying to populate values for html drowpdown using JQuery from webapi url. JSON returns value and I've verified it using alert function. But, when I bind those into dropdown it is not populating the values.

    Chrome developer tool console shows err:

    "Cannot read property '0' of undefined ".

    @section scripts {
    
    <script src="~/Scripts/jquery-1.8.2.js" type="text/javascript"></script>
    <script src="~/Scripts/jquery-ui-1.8.24.min.js" type="text/javascript"></script>
    
    <script type="text/javascript">
    
        $(document).ready(function() {
            var testDdl = $('#test');
            $.ajax({
                url: "/api/Values",
                type: "Get",
                success: function(data) {
                    for (var i = 0; i < data.length; i++) {
                        testDdl.append($("<option/>"), {
                            value: this.data[i],
                            html: this.data[i]
                        });
                    }
                },
                error: function(msg) { alert(msg); }
            });
        });
    </script> }
    
    <body>
    
    <form>
        <select id="test"></select>
    </form> </body>
    

    Please help me to resolve this.