views:

88

answers:

4

I have a basic DOM "outline" that contains a table with dummy data like this:

<table>
  <tr>
    <td>name</td>
    <td>phone</td>
  </tr>
</table>

My script uses this as a dummy row to clone and replace the text between the TD tags with text from a database. Without copying the whole script here, here are two different things I've tried:

newRow.find("td.name").text(participant.name);

newRow.find("contains("phone")").text(participant.homePhone);

Neither one works. The script clones and displays the rows just fine, but I have 30 rows of "name" and "phone".

I used Firebug's console.log to debug and I am sure that it's got the data correctly from JSON, loaded into the "participant" parameter. What am I doing wrong?

+6  A: 

you're using td.name which doesn't exist in your markup. the .name denotes a class so you'd need markup like: <td class="name"></td> in order for that to work.

If you're using this as a dummy row and replacing those two td's, I'd supply a class to each like <td class="name"></td><td class="phone"></td> to use newRow.find("td.name") or use something like: newRow.find("td:first") and newRow.find("td:last")

brad
A: 

find('td.name') looks for a td with a class="name", which you don't have. I would recommend adding this to your HTML to create a hook for jQuery to update the text. Especially if you have several on the page.

Also, how are you setting newRow?

Jason McCreary
+2  A: 
newRow.find("td:contains(name)").text(participant.name);

newRow.find("td:contains(phone)").text(participant.homePhone);
Scott Evernden
Now, what would happen if the participants name is Stephone Andrews?
Gert G
Scott Evernden
@Gert G - you're right. I wasn't thinking.
tvanfosson
+1  A: 

The second version is almost right if I understand what you are tring to do. Note the colon preceding the selector and the use of inner single quotes.

newRow.find(":contains('name')").text(participant.name);
newRow.find(":contains('phone')").text(participant.homePhone);

Better yet would be to give the templates classes and use those or simply rely on the positioning.

Positioning:

newRow.find('td:first-child')
      .text(participant.name)
      .next()
      .text(participant.homePhone);

Classes:

newRow.find( 'td.name' ).text( participant.name );
newRow.find( 'td.phone' ).text( participant.homePhone );

Necessitating this change:

<table> 
  <tr> 
    <td class="name">name</td> 
    <td class="phone">phone</td> 
  </tr> 
</table>
tvanfosson
Thanks. I picked this one as the answer, although almost everybody told me to use classes. Of course! It's working now.
Carrie Cobol
@Carrie - Note that classes are a good way to do it. I wouldn't use the `contains` method as you might have issues if someone's name includes the string `phone`, for instance. The DOM-relative mechanism works well but is sensitive to changes in the table structure.
tvanfosson