Reputation: 25
I want to transform an xml document into an HTML table using jquery/ajax. Additionally I want to add a class to the tr
if a condition is met. This is what I've done so far, but it doesn't work as intended: 1) the HTML table output has more tr
and td
than it should have and 2) the conditional classes for the tr (.no-kids
) aren't working.
Any help would be appriciated!
JQUERY/AJAX CODE:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "database.xml",
dataType: "xml",
success: function(xmlData) {
$("person", xmlData).each(function(){
var name = $(this).find("name").text(),
kids = $(this).find("kids").text(),
cars = $(this).find("cars").text();
if(kids<1){
$("tbody").append('<tr class="no-kids">');
}else{
$("tbody").append('<tr>');
}
$("tbody tr").append('<td class="name">'+name+'</td>');
$("tbody tr").append('<td class="kids">'+kids+'</td>');
$("tbody tr").append('<td class="cars">'+cars+'</td>');
$("tbody").append('</tr>');
});
}
});
$(".no-kids").css("color","red");
});
HTML CODE:
<table>
<thead>
<tr>
<th>NAME</th>
<th>KIDS</th>
<th>CARS</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
DATABASE.XML CODE:
<root>
<person>
<name>Matt</name>
<kids>3</kids>
<cars>1</cars>
</person>
<person>
<name>Jason</name>
<kids>0</kids>
<cars>2</cars>
</person>
<person>
<name>Molly</name>
<kids>1</kids>
<cars>0</cars>
</person>
</root>
Upvotes: 1
Views: 5448
Reputation: 95027
jQuery only appends whole elements, not starting/ending tags.
var output = '<tr' + parseInt(kids) < 1 ? ' class="no-kids">' : '>';
output += '<td class="name">'+name+'</td>';
output += '<td class="kids">'+kids+'</td>';
output += '<td class="cars">'+cars+'</td>';
output += '</tr>';
$("tbody").append(output);
Edit: Additionally, you need to apply the red font color in the success callback.
}
});
$(".no-kids").css("color","red");
});
should be
$(".no-kids").css("color","red");
}
});
});
Upvotes: 4