0

I have gone mad trying to bind the json string to the dropdown. Please can somebody help??

My dropdownlist id is 'ddlteams'

My json string is in this form :

"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

so first i convert into an object.

var objdata = $.parseJSON(jsonObj.d);

Then i add my code given below.

$('#ddlteams').children().remove();

I am having problem with the below code. Please can somebody help me with this

$.each(objdata, function(i, val) {
    $('#ddlteams').append('<option value="' + objdata.TeamList[0].teamid + '">' + TeamList[0].teamname + '</option>');
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
jith10
  • 553
  • 3
  • 11
  • 17
  • Assuming `objdata` is the parsed JSON, `i` will be `"TeamList"` and `val` will be the array. Have a look at the documentation of `each`. Just iterate normally over `objdata.TeamList`. – Felix Kling Feb 06 '12 at 19:20
  • Hi Felix, sorry but i did not get you. do i need to replace i with "TeamList"?? is val a keyword in there?? – jith10 Feb 06 '12 at 19:24
  • You are using `$.each` but it does not seem you know how it works. It will iterate over each property of the object or element of the arrays passed. The property name and its value are passed to the callback function as arguments, in your case `i` and `val`. – Felix Kling Feb 06 '12 at 19:29
  • Hi Felix. agree with you. started learning jquery very recently. i ll try that! – jith10 Feb 06 '12 at 19:34

1 Answers1

4

try

$.each(objdata["TeamList"], function(i, val) {
    $('#ddlteams').append('<option value="' + val.teamid + '">' + val.teamname + '</option>');
});
Will
  • 7,225
  • 2
  • 23
  • 14
  • Perhaps `$('#ddlteams').append('');`? I'll try to reproduce what your working with and help you get it running. – Will Feb 06 '12 at 19:40
  • 1
    `val['teamid']` is the same as `val.teamid`. – Felix Kling Feb 06 '12 at 19:41
  • Hi.. We are very near. I have some 5 items to be displayed. I did this -> $.each(objdata, function(i, val) { $('#ddlteams').append(''); }); and i got the first result. Now to get the other items i tried to declare a variable and assign it to 0 and then incremented it by 1. but its not working – jith10 Feb 06 '12 at 19:45
  • You don't mean to iterate through each of `objectdata` you mean to iterate through `ojectdata.TeamList`. Look again at the answer I gave. – Will Feb 06 '12 at 19:50