0

I have this JSON string (coming out of a DataSet, 1 column, a few rows -showing just 2 for the example-)

{"Tables":[{"Rows":[{"Column1":"UserNumer1"},{"Column1":"UserNumber2"}]}]}

How can I use those values in my dynamically populated select value?

$('<option>').val('UserNumer1').text('UserNumer1').appendTo('#selectID');

I want to append all values, if JSON string has 10 rows (users in this case) I'd like the jquery to append to my selectID all of the rows. Was told it's better to appendTo just once instead of doing an interation.

Thanks!

EDIT based on Answer.

For quick testing purposes I set on my Page Load this.

jsonString = GetParsedData();

Now, the jQuery script.

$(function () {
        var obj = <%=jsonString%>;
        var html = "";
        for (var i = 0; i < obj.Tables.length; i++) {
            html += '<option value="' + obj.Tables[i].Column1 + '"> ' + obj.Tables[i].Column1 + '</option>';
        }
        $(html).appendTo('#selectID');
    });

The list is not getting populated, so I tried firebug, and after a breakpoint I get this result for the variable html

"<option value="undefined"> undefined</option>"

the var obj is OK

{"Tables":[{"Rows":[{"Column1":"UserName1"},{"Column1":"UserName2"}]}]};

Am I missing something here? Thanks a lot.

Besides de "undefined" which is wrong, it's not even appending it. Menus list y empty.

1 Answer 1

3
 var table;   for (var i=0; i< resp.Tables.length; i++){
     table = resp.Tables[i];
     for(var j=0;j<table.Rows.length; j++ ){
          $('<option>').val( table.Rows[j].Column1).text(table.Rows[j].Column1).appendTo('#selectID');
    }
    }

I suggest you faster way.

var html = "";
    for (var i=0; i< resp.Tables.length; i++){
    table = resp.Tables[i];
     for(var j=0;j<table.Rows.length; j++ ){
         html +='<option value="'+  table.Rows[j].Column1 +'"> '+  table.Rows[j].Column1 +'</option>';
    }
    }
$(html).appendTo('#selectID');
Sign up to request clarification or add additional context in comments.

3 Comments

You changed the format of JSON object. I modifiied my code accordingly.
Not working. After your edit, now html is totally empty. And the JSON object (var obj here) was never modified. I copied and pasted your code, changed resp for obj and no, no working. Any clue?
Done! you were right about the JSON, my bad. Great work, thanks a lot.

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.