What is the best way to alter the BackColor of a dropdown list item depending on the variance between the date on the list and the current

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>

`

Answer №1

Enhancing the appearance of a default select option using CSS is a simple task. Here's the code snippet where I delved into the requirements and found a solution. Providing an answer to my own query just in case there are suggestions for improvement.

$(document).ready(function () {
            $("#ddldueDate > option").each(function () {
                //Extracting DueDate - type string
                var SelectedGroup = $(this).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;
                if (days < 1) {
                    $(this).css({ "background-color": "maroon" });
                    $(this).css({ "color": "white" });
                } else {
                    $(this).css({ "background-color": "white" });
                    $(this).css({ "color": "black" });
                }
            });
        });
<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>[2020-07-27] Test 1</option>
      <option>[2021-07-24] Test 2</option>
      <option>[2019-07-27] Test 3</option>
      <option>[2019-07-24] Test 4</option>
    </select>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing page loading with images for optimal user experience

Currently, I am working on a website that requires users to navigate through multiple pages by using next and previous buttons. Initially, I attempted to implement a Java slideshow for this purpose, but encountered issues with creating hashtags and social ...

Error encountered when attempting to send a jQuery Post to API due to Access-Control-Allow-Origin issue

I've been researching the 'Access-Control-Allow-Origin' error extensively, but I am still struggling to understand what needs to be fixed. Here's the code snippet in question: $.ajax({ url: 'http://54.149.190.45:8000/image/upl ...

Allowing breaks with the :nth-child() selector

There must be a straightforward explanation for this perplexing issue. However, in my view, it ought to function as intended. We are currently utilizing the Bootstrap 3 CSS framework. The following code is present on a specific page: <div class="promo ...

Displaying data in JSON format retrieved from a MySQL database

Greetings everyone! I am currently working on a website built with CodeIgniter. In one of my functions, I need to fetch data from MySQL and display the result in JavaScript as part of an Ajax call. Here is my PHP function for retrieving data: public func ...

Error with HTML form validation

After clicking the "Send Request" button, the query string ?req_flag=0 is not appearing in the URL. What could be causing this issue? I want my URL to look like this: localhost/flavourr/send_req.php?req_flag=0&f_e_mail_add=value <pre> <form ...

Step-by-step guide on building an engaging Donut chart using jQuery

After spending several hours working on it, I'm struggling to draw my donut graph with JavaScript. Can anyone provide a solution? I am looking for a way to add 25% when one checkbox is selected and +25% when two checkboxes are selected. Thank you in a ...

What is the process for integrating this graph using highcharts?

Check out this link for more information on investment decision-making. There is a visually appealing graph and pie chart featured in the section about Investment Decision-Making in 2016. After noticing that it was created using Highcharts, I wanted to c ...

I'm looking to keep the footer anchored at the bottom without using the absolute positioning

I am currently developing a website and have implemented a wrapper for the footer. My goal is to create a sticky footer, but when I minimize the screen, the footer ends up overlapping with the content and header. #footerWrapper { height: 177px; bottom: ...

Animation not properly synced with Bootstrap 4 Dropdown hide event

Could you please check out my codepen for clarification: http://codepen.io/anon/pen/oLZOyp Essentially, I have integrated two animations using animate.css into Bootstrap 4 show.bs.dropdown and hide.bs.dropdown events. The animations work on the first show. ...

Troubleshooting: :before element not being hidden by jQuery slidetoggle()

My elements are all behaving correctly with the slidetoggle() function, except for my li:before class. I've attempted to manipulate the overflow, visibility, display, and other properties of both the :before pseudo-element and the li element, but the ...

It can be challenging to manage numerous if-else conditions in JQuery

I am having trouble with my JQuery code that checks multiple conditions. No matter what I enter, it always goes to the else condition. $(function() { $('#installment').on("keydown keyup", check); function check() { var inst = Number($( ...

Tips for maintaining the aspect ratio of an image while ensuring it always occupies 100% width and automatically adjusts its height

I've searched everywhere but can't seem to find the right CSS solution for my problem. How can I ensure that an image always fills 100% of the height and width of the screen while maintaining its aspect ratio? .myimage { object-fit: cover; widt ...

Using jQuery to dynamically add `<option>` elements with both disabled and selected attributes

After successfully appending an <option> element to my <select> tag with its corresponding value, text and placeholder attributes, I encountered some difficulty in determining the correct keyword for setting the disabled and selected properties ...

Anchor elements and other inline elements not triggering MouseLeave event

Take a look at this CodePen link, particularly in Chrome: https://codepen.io/pkroupoderov/pen/jdRowv Sometimes, the mouseLeave event doesn't trigger when a user quickly moves the mouse over multiple images. This results in some images still having t ...

Why isn't the input appearing on the succeeding line below?

<label for="email2">Enter Your Email Address</label> <input type="text" name="email2" id="email2" placeholder="example: [email protected]"> <label for="phone2">Phone Number</label> <input type="text" name="phone2" id= ...

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

Sending a JSON array to a WebMethod

I encountered an issue when attempting to convert an object to a JSON array as a string, resulting in an Internal Server Error. Fortunately, the GetServerTime method is functioning properly. My goal is to send an array of objects to the server and conver ...

Aligning two lines next to a radio button using HTML and CSS

I'm facing a challenge where I want to align two lines in the middle of a radio button. Despite my efforts, I am able to line up the top line but struggling with the bottom one. I prefer not floating the radio button as it's being styled using a ...

Is there a method in AngularJS to submit form data when the input fields are pre-populated using a GET request?

How do I submit form data in AngularJS? I have a div that populates the input field from a GET request. Now, I want to send this data using a POST method. How can I achieve this? Below is the form div: <div class="row" ng-app="myApp" ng-controller="myC ...

Learn the process of extracting a particular value from JSON data and displaying it in HTML by utilizing AngularJS's ng-repeat directive

As a newcomer to angularjs, I am encountering difficulties retrieving and displaying a specific value from a json file in order to showcase it on my view page using angularjs ng-repeat for image source. My goal is to repeat the json file based on a particu ...