Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I apply a jQuery function to all elements with the same class.?

JQuery return value for all same name class = 2.53 (first element value applied for all Span)

How do I get different values?

(Edit:) HTML code:

<div class='ratingInfo'>
    <table class='rating_table' border='0' cellpadding='0' cellspacing='0'>
      <tbody>
        <tr>
          <td>
             <div class='review-rating'>10</div>
          </td>
          <td>
             <div class='stars1'></div>
          </td>
        </tr>
      </tbody>
    </table>
</div>


<div class='ratingInfo'>
    <table class='rating_table' border='0' cellpadding='0' cellspacing='0'>
       <tbody>
          <tr>
            <td>
                <div class='review-rating'>1</div>
            </td>
            <td>
              <div class='stars1'></div>
            </td>
          </tr>
        </tbody>
     </table>
 </div>

JavaScript

 $( document ).ready(function() {
    $( ".stars1" ).html("<span class='stars'>"+$('.review-rating').text()+"</span>");
    $('span.stars').stars();
 });

 $.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('<span />').width(Math.max(0, (Math.min(5,   parseFloat($(this).html())))) * 16));
    });
 }
like image 635
rf jm Avatar asked Dec 05 '25 12:12

rf jm


1 Answers

Because $('.review-rating').text() is grabbing the first element every time, it does not know you want the one that is beside the element. You need to code it to look there.

$( ".stars1" ).each( function () {
    var star = $(this);
    star.html("<span class='stars'>" + star.prev('.review-rating').text() + "</span>");
});

with the new HTML code, the above will not work since the elements are NOT siblings. That is why it is important to have the actual code! You need to look for a common parent and find the element within it, in this case you have the TR that contains both. So to get the parent, use closest()

$( ".stars1" ).each( function () {
    var star = $(this);
    var rating = star.closest("tr").find(".review-rating").text();
    star.html("<span class='stars'>" + rating + "</span>");
});
like image 130
epascarello Avatar answered Dec 07 '25 02:12

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!