I have a dropdown list in (MVC View file & using jQuery); that contains text along with a date substring in the format "yyyy-MM-dd". I am able to extract the date, compare it with the current date, and calculate the difference. Based on this difference, I want to change the background color of the dropdown item.
I store the due date substring in a variable and fetch the current date to calculate the difference. If the due date is less than 1 day from the current date, I want to set the background color of that particular item to red. Although the code enters the if statement when the condition is true and the alert message works, the code to change the background color does not.
Only the dropdown item with a due date that has already passed should have a red background color. The jQuery snippet below is meant to achieve this:
$(document).ready(function () {
$("#ddldueDate").each(function () {
//Extracting DueDate - type string
var SelectedGroup = $(this).children("option").text();
var dueDateStr = SelectedGroup.substring(SelectedGroup.lastIndexOf('[') + 1, SelectedGroup.lastIndexOf(']'));
//Get current date - type string
var d = new Date();
var month = d.getMonth() + 1;
var date = d.getDate();
var currDateStr = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (date < 10 ? '0' : '') + date;
var diff = new Date(Date.parse(dueDateStr) - Date.parse(currDateStr));
var days = diff / 86400000;
//alert(days);
if (days < 1) {
$(this).children("option").css({ "background-color": "red" });
} else {
$(this).children("option").css({ "background-color": "white" });
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-12" style="width:auto">
<select id='ddldueDate' class='form-control'>
<option>[2019-07-27] Test 1</option>
<option>[2021-07-24] Test 2</option>
</select>
</div>
</div>
`