duke duke - 1 year ago 55
jQuery Question

how to add rating funtion to particular td in $.each function

I want to know how to select particular td in table.

$.each(result.HotelSearchResult.HotelResults, function (index, item) {
var imgPath = item.HotelPicture;
var rate = item.StarRating;
var table = $('#tableId');
var rows = '<tr><td rowspan="4" width="16.666%"><img src="' + imgPath + '" />'+ "</td>";
rows += '<tr><td class="code">' + addScore(rate, $("td.code")) + "</td></tr>";

is a function and it requires an element as its second parameter to append stars according to rating. I am following this post, but in my code it is appending all the ratings to particular
for each iteration. This means if there are 20 arrays then its appending 20 ratings to each
in the table. I want to append one rating per

This is my table:

<div id="divResult5"></div>
<tbody id="tableId" style="border:solid 1px red;"></tbody>

Please tell me how it should be done.

Answer Source

You can modify addScore as below and try:

function addScore(score) {
 var className = 'stars-container stars-'+score.toString();
 return "<span class='"+className+"'>★★★★★</span>";

And invoke addScore as below:

rows += '<tr><td class="code">' + addScore(rate) + '</td></tr>';

Here is the reason why the original function is not working: The original function was expecting a DOM element as second argument, and it appends the score span element to the DOM element.

In your case when you are sending $("td.code") there are two problems associated with it: The selector "td.code" will select all td-elements whose class is ".code" which means it behaves as below :
=> when it iterates first row, it will not find any td element because the current td element is not yet in DOM.
=> when it iterates second row, it will not find current td element but it will find td element of the first row because the first row td-element is also having the same class ".code"
=> when it iterates nth row, it will not find current td nth element but it will find td elements of the (n-1) rows

So as current td element to which you are trying to append stars is not yet in DOM, you cannot pass that as second argument.

Instead you need a function that will generate HTML markup (span with stars) and you can directly invoke that function, addScore(score) will return the markup.