Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
    
What does console.log(data) give you if you place it inside the success callback? –  Kristoffer Jun 23 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. –  Freesiah Jun 23 at 19:43
    
I do have 2 values in my json. So, console gives "Value1, value2". –  Freesiah Jun 23 at 19:47
add comment

2 Answers

up vote 1 down vote accepted

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|improve this answer
    
Thank you very much. It is working!!! –  Freesiah Jun 23 at 20:09
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.