Carter Steinhoff Carter Steinhoff - 1 month ago 7
jQuery Question

How can I convert value of attribute into a integer using Jquery?

I have created a function that is supposed to find the value of attributes and output the average. Right now, this is not working. I believe it has to do with how I am selecting the attribute.

Here is the fiddle - https://jsfiddle.net/carbot3000/0kjLu3h0/7/

I need help identifying what I'm doing wrong. An updated fiddle would also be very helpful.

var total = 0,
valid_labels = 0,
average;

var reviewAverage = $('meta[itemprop="ratingValue"]').attr('content');

$(reviewAverage).each(function () {
var val = parseInt(reviewAverage), 10);
if (val !== 0) {
valid_labels += 1;
total += val;
}
});

average = total / valid_labels;
$(".reviewRating").val(average);

Answer

A snippet of your HTML:

<meta content="5" itemprop="ratingValue">

With this line

var reviewAverage = $('meta[itemprop="ratingValue"]').attr('content');

You're receiving a collection of jQuery objects from $('meta[itemprop="ratingValue"]') and then trying to run a method built for a singular object. Furthermore, your content attribute is a number, so running $(5) isn't going to help either.

You can get all of your ratings to a regular array with $.map - and then run a reduce function:

var reviewRatings = $('meta[itemprop="ratingValue"]').map(function() {
    return $(this).attr("content");
}).get();

var reviewAverages = reviewRatings.reduce(function(total, rating) {
    return total += parseInt(rating, 10);
}, 0) / reviewRatings.length;