2

I''ve been working on this all day long and haven't get it yet. I have this code to load and display some JSON data:

var id = firstLevel.id;
$.each(thirdLevel, function(index4, fourthLevel) {
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>");
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>");
    currentRow++;
    console.log(id);
});

It's supposed to insert new columns to a row using the id of the table (I have a lot of tables with different ids each one) but the "id" variable doesn't seem to be working right, and I'm printing it to console and it has the right value (421 in the first iteration)

Now, if I do this:

var id = 421;
$.each(thirdLevel, function(index4, fourthLevel) {
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>");
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>");
    currentRow++;
    console.log(id);
});

It will work, and insert all the new columns on the table with id 421...

So, is there something wrong with my code? Thank you very much!

Multitut
  • 2,089
  • 7
  • 39
  • 63
  • 1
    what are you working on where both "male" and "herm" are options? lol – Jason Nov 04 '11 at 22:11
  • Would be nice to know what firstLevel is – Dr.Molle Nov 04 '11 at 22:22
  • what % of the internet market does porn occupy? C'mon! @user937471: what if you name your variable something other than id? – Will Nov 04 '11 at 22:23
  • 1
    They are genres of worms, there are no female worms :P. I named TableId as well and the same happened. – Multitut Nov 04 '11 at 22:27
  • Are you able to post a full example that reproduces the problem at all? If not, can you post the JSON you're receiving and a bit more of the function around the code you've post and an example of the HTML you have. Right now, nothing obvious jumps out. – Alex Taylor Nov 10 '11 at 09:09

2 Answers2

1

EDIT: As ZenMaster points out in the comments, as you're not using id as a number, this is definitely not the issue.

It is quite likely that the data you are pulling out is indeed a string, you'd need to show what your JSON looked like. If that is the case, you'll want to use the parseInt function to tell javascript to parse the string as an integer.

var id = parseInt(firstLevel.id);
$.each(thirdLevel, function(index4, fourthLevel) {
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>");
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>");
    currentRow++;
    console.log(id);
});

Alex Taylor
  • 1,823
  • 1
  • 13
  • 26
1

First of all numeric IDs are invalid. So do not use them..

Secondly make sure the firstLevel.id does not have trailing or leading whitespace ..

try console.log(id, id.toString().length); and see if the length is indeed 3

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317