March 4, 2012

How to properly apply values farmed from .each()

Question by Morningseven

Markup:
<ul>
  <li>
    <ul id="ratx">
      <li>Location</li>
      <li class="bar"><span></span></li>
      <li class="value">4</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
     <li>Hotel Services</li>
     <li class="bar"><span></span></li>
     <li class="value">5</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Hotel Facilities</li>
      <li class="bar"><span></span></li>
      <li class="value">3</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Room Cleanliness</li>
      <li class="bar"><span></span></li>
      <li class="value">4</li>
    </ul>
  </li>
  <li>
    <ul id="ratx">
      <li>Value for Money</li>
      <li class="bar"><span></span></li>
      <li class="value">1</li>
    </ul>
  </li>
</ul>

I want to represent User Ratings dynamically using JQuery so I made a function like this,

jQuery:
$("ul#ratx").each(function(index) {
var val = $(this).children(".value").text();
var barval = val * 40;

/* compute ratings */ 
$("li.bar span").css("width", barval);

});

Now, when I alert barval I get all 5 values but when I try to apply the “compute ratings” line, all it does is apply the last value that it finds. How should I go about this?

Sorry if the question is a confusing. I am not quite sure how to phrase everything.

Answer by Starx

The problem is that, while interating through each elements it find, it is applying a common value to all li.bar span. You should represent a single element, you are trying to apply to.

$(this).children(“li.bar span”).css(“width”, barval);

Update

Here is a working Demo

The snippet that worked was

$(this).find("li.bar").children("span").css("width", barVal );

Also, I changed the display property of the span to display: inline-block;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!