Reputation: 311
I have a table with Entries. Each entry has a datetime, text, calory. I need to make all rows green, if total calories for that day is less than expecting value, otherwise make it red. In my index action I have @total (which is the value to compare with) and in the end I have two arrays with good (green) dates and bad dates.
def index
@entries = Entry.all
@total = 50
@total2 = Entry.all
@a = {}
Entry.all.each do |entry|
if @a.key?(entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10])
@a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += (entry.calory)
else
@a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] = 0
@a[entry.time.strftime("%Y-%m-%d %H:%M:%S")[0..10]] += entry.calory
end
end
@good = []
@bad = []
@a.each do |c|
if c[1] < @total
@good.append(c[0])
else
@bad.append(c[0])
end
end
end
Then in my index.html.erb I loop through the rows and try to change it's color, if the value is in good or bad array. But it colors everything green.
<script type="text/javascript">
var a = '<%=@a%>';
var final = '<%=@final%>';
var good = '<%=@good%>';
var bad = '<%=@bad%>';
console.log(good);
$('#entries tr').each(function() {
var date = $(this).find("td:first-child").text();
if (good.substring(date) !== -1) {
$(this).find("td:first-child").addClass('good');
} else {
$(this).find("td:first-child").addClass('bad');
}
});
</script>
Here is my table
Time Text Calory Show Edit Destroy
2016-12-24 10:00:00 first 23 Show Edit Destroy
2016-12-24 11:58:00 second 45 Show Edit Destroy
2016-12-24 12:59:00 third 56 Show Edit Destroy
2016-12-28 12:29:00 sds 34 Show Edit Destroy
2016-12-24 10:00:00 dewq 34 Show Edit Destroy
Here is console.log(good): ["2016-12-28 "] Here is console.log(bad): ["2016-12-24 "]
Here is console.log(date) for each date:
2016-12-24 10:00:00
2016-12-24 11:58:00
2016-12-24 12:59:00
2016-12-28 12:29:00
2016-12-24 10:00:00
Upvotes: 0
Views: 612
Reputation: 12305
You just need to use indexOf
; based on your sample data this should works:
$('#entries tr').each(function() {
var date = $(this).find("td:first-child").text();
if(date.indexOf(bad[0].toString()) > -1){
$(this).find("td:first-child").addClass('bad');
}
if(date.indexOf(good[0].toString()) > -1){
$(this).find("td:first-child").addClass('good');
}
});
Upvotes: 1