4

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.

4
  • stackoverflow.com/questions/9275972/… Commented Jun 23, 2014 at 19:36
  • What does console.log(data) give you if you place it inside the success callback? Commented Jun 23, 2014 at 19:39
  • I tried the above link opt.text = data[i]; opt.value = data[i]; testDdl.options.add(opt);. But, I am getting "Cannot read property 'add' of undefined" error. Commented Jun 23, 2014 at 19:43
  • I do have 2 values in my json. So, console gives "Value1, value2". Commented Jun 23, 2014 at 19:47

2 Answers 2

2

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/

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

Comments

0

Iterate through the result with $.each.

$.each(data, function(key, value) {
    console.log(key);
    console.log(value);
}

What you should pass to testDdl.append depends on what your JSON looks like.

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.