I'm struggling with what is probably a very simple bit of jQuery
I have html like this:
<div class="star-rating" data-star-rating="5.0"></div>
<div class="star-rating" data-star-rating="2.0"></div>
I have some javascript which needs to do something based on the star rating of each of these elements and currently looks like this:
$('.star-rating').jRate({
startColor : '#ccc',
endColor : '#ccc',
readOnly : true,
rating : <value of data-star-rating>
});
I want to replace <value of data-star-rating>
with the value of the data attribute relating to the element currently being processed
I thought this would work $(this).data('starRating')
but it doesn't seem to
How can I access the value of the data attribute in this situation?
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
You can use this too :
$(this).data('star-rating');
EDIT
After reading again the question. Comments are right, you should iterate through .star-rating
array to apply the jRate to each element, sorry for my misunderstanding.
$('.star-rating').each(function () {
$(this).jRate({
startColor: '#ccc',
endColor: '#ccc',
readOnly: true,
rating: $(this).data('star-rating')
});
});
$(this)
doesn't refer to the element on which the jRate
function is being called.
You can use the selector if there is only a single element having that class
$('.star-rating').jRate({
startColor : '#ccc',
endColor : '#ccc',
readOnly : true,
rating : $('.star-rating').data('star-rating')
});
For multiple elements:
Iterate over all the elements having the class star-rating
and attach the plugin jRate
individually with the rating
value of the respective element.
$('.star-rating').each(function () {
$(this).jRate({
startColor: '#ccc',
endColor: '#ccc',
readOnly: true,
rating: $(this).data('star-rating')
});
});
JSFiddle DemoDidn't find CDN link of that plugin, so added the minified code in JavaScript pane itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With