javascript - Conditional Alert in HTML Table -
this question has answer here:
i have managed automatically build html table based on output erp system, , managed use css format easily. last step conditional formatting in date field. if date < make field red if it's between 4 <> 7 days make yellow else "no formatting.
i have gotten far on dozens of examples site, , hoping can me basic date math reason can't head around.
right date field in td:nth-child(4) , want compaire current date.
<script> $(document).ready(function() { $('table td:nth-child(4)').each(function() { var d1 = $(this).text(); var d2 = new date(); if ((d1 - d2) < 4) { $(this).css('backgroundcolor', 'red'); } else if((d1 - d2) < 7) && ((d1 - d2) > 4) { $(this).css('backgroundcolor', 'yellow'); } else { $(this).css('backgroundcolor', '#99faa0'); } }); event.preventdefault(); }); </script>
you need convert , compare dates properly. below example compare dates.
reference:
get difference between 2 dates in javascript?
var _ms_per_day = 1000 * 60 * 60 * 24; // , b javascript date objects function datediffindays(a, b) { // discard time , time-zone information. var utc1 = date.utc(a.getfullyear(), a.getmonth(), a.getdate()); var utc2 = date.utc(b.getfullyear(), b.getmonth(), b.getdate()); return math.floor((utc2 - utc1) / _ms_per_day); }
working sample