Ron
Ron

Reputation: 69

jQuery + Rails: variable selector doesn't work

I am trying to record the score of a specific route after the user clicks on a star.

$('.ratings_stars').on('click', function() {
        var score=$(this).attr("data-score");
        var route_id=$(this).attr("data-route_id");
  });

It does record the score, but it either selects only "1" or "0" for the route or leaves it empty.

Scores

I have tried the following:

var route_id=1; // displays "1" as to be expected
var route_id='#'; // displays "0"
var route_id=$(this).attr("data-route_id"); // no link to any route
var route_id=$(this).attr("route_id"); // no link to any route

Can anyone see what I don't see?

Edit: I have posted the whole code here jsfiddle

Many thanks.

The solution: var route_id=$(this).parent().attr("id").replace('Route', '');

Upvotes: 0

Views: 158

Answers (1)

acdcjunior
acdcjunior

Reputation: 135862

Based on the comments and on this fiddle http://jsfiddle.net/45AEY/:

<h3 class="bar">Beginners</h3>
<div class="content">
    <ul>
    <li><a href="#/routes/1">Route 1</a>
        <div id="Route1" class="rate_widget">
        <div class="star_1 ratings_stars" data-score="1">1</div>
        <div class="star_2 ratings_stars" data-score="2">2</div>
        <div class="star_3 ratings_stars" data-score="3">33</div>
        <div class="star_4 ratings_stars" data-score="4">44</div>
        <div class="star_5 ratings_stars" data-score="5">55</div>
        </div>  
        <div class="total_votes">vote data</div>        
    </li>
    </ul>
</div>

As there are no data-route_id attributes, I believe the route_id you are trying to catch is the number of the Route of the parent div (in the example above, the parent div is <div id="Route1" class="rate_widget">.

In that case, this line

var route_id = $(this).attr("data-route_id");

Can be switched to this line:

var route_id = $(this).parent().attr('id').replace('Route','');

And route_id will have the ID of the route. (In the example above it'll be 1).

Give it a go: http://jsfiddle.net/2B9GM/

Ps.: In your original fiddle, you did not set jQuery as library. Make sure you have it set in your fiddles and, more importantly, imported (through the script tag) in your HTML page.

Upvotes: 1

Related Questions