Applying CSS selectively based on conditions with the SELECT OPTION statement

For my array of locations, I am attempting to style location two in a unique way - with a deleted look featuring a red background and white text that is crossed out. When this option is selected by the user, I want the closed dropdown to display the same red crossed out label.

This is the desired appearance when the dropdown is closed:

However, I have encountered two issues with my code. First, the text-decoration: line-through styling is not being applied to the option that should look deleted, despite the red background and white text being styled correctly by the .isDeleted CSS class.

Secondly, when the deleted option is selected, the closed dropdown does not reflect any of the option styling. Instead of appearing with a red background and white crossed out text as intended, the text is black with a white background.

The image below shows the dropdown open, with the cursor hovering over the first option highlighted in blue, while the deleted option is displayed in red without the necessary crossing out effect. I'm unsure why this is happening even though the class is being applied.

I also attempted adding the class styling to the select element instead of the option element, but this resulted in all options being changed once the deleted style was applied.

View the Plunker Demo

$scope.locations = [
    {"label":"123 Main St","locno":1,"deleted":false},
    {"label":"456 Main St","locno":2,"deleted":true},
    {"label":"789 Main St","locno":3,"deleted":false}
];

$scope.oItem = {"itemName":"Strawberry","locno":2};
.isDeleted{
    background-color:red;
    color:white;
    text-decoration: line-through !important;
}
.isNotDeleted{
    background-color:white;
    color:black;
    text-decoration: none;
}
<select  ng-model="oItem.locno">
    <option disabled value="">select location</option>
    <option ng-repeat="opt in locations" 
            ng-value="{{opt.locno}}" value="{{opt.locno}}" 
            ng-class="{'isDeleted':opt.deleted, 'isNotDeleted':!opt.deleted}">{{opt.label}} -- {{opt.deleted}}</option>
</select>

Answer №1

Unfortunately, the element select can be quite challenging to style due to its inherent nature.

Styling the select element consistently across different platforms is notoriously difficult. However, there are some workable styles that you can apply.

Reference: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Advanced_styling_for_HTML_forms

You may encounter limitations with CSS properties like text-decoration when styling the option elements within a select. One potential solution could be creating a custom directive in AngularJS to simulate the functionality of select/options or utilizing frameworks like Bootstrap.

To address the second issue, I have made adjustments to your code below:

<select  ng-model="oItem.locno" ng-class="styleOItem" class="selectedValueDeleted" ng-change="styleSelectOnChange()">
        <option disabled value="">select location</option>
        <option ng-repeat="opt in locations" 
                ng-value="{{opt.locno}}" value="{{opt.locno}}" 
                ng-class="{'isDeleted':opt.deleted, 'isNotDeleted':!opt.deleted}">{{opt.label}} -- {{opt.deleted}}</option>
      </select>

Adjusted JavaScript code:

$scope.styleSelectOnChange = function() {
    angular.forEach($scope.locations, function(loopedObject) {
      if (loopedObject.locno === $scope.oItem.locno) {
        if (loopedObject.deleted) {
          $scope.styleOItem = "isDeleted";
        } else {
          $scope.styleOItem = "isNotDeleted";
        }
      }

    });
  };

Check out the Plunker for a live demonstration:

I have introduced the use of ng-class to dynamically apply classes based on certain conditions. The class determination logic is encapsulated within the 'ng-change' event handler of the 'select' element.

If you require further clarification or if I have misinterpreted your concerns, please let me know.

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

Embed the script in the Froala Editor to add text content

Having an issue with integrating external content into Froala 3 while using AngularJS. Currently, I am facing a challenge in adding predefined messages from a modal exactly where the cursor is located within Froala editor. Right now, the message gets ins ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

Does embedding an Iframe for external files from your server enhance the loading speed of the current page compared to directly loading it on the page?

I'm facing an issue with the loading time of a Facebook post on my webpage index.php. The current method of using the embedded post provided by Facebook is taking too long to load. My solution is to create a separate page, post.php, where only the Fac ...

Instructions for showcasing a specific entry from the json server db.json based on user input

Currently, I am capturing user input from an input component and I would like to display the corresponding information on a display component in my Angular application. The user records are stored in a JSON server named db.json. Does anyone know how I can ...

- Removing the img tag from an HTML document: A guide

When I use quick watch, this is the innerHtml output: <img style="width: 100%; height: 320px;" src="img/banner03.jpg"> <div class="bjqs-caption"> Automatically generated caption3 </div> However, I want the innerHTML to b ...

Encountering iOS 10 freezing issues when scrolling through an HTML list that is styled with -webkit-overflow-scrolling: touch

Overview This specific issue pertains to a potential freeze that occurs when scrolling through a <ul /> element that has been styled using CSS, specifically with the property -webkit-overflow-scrolling: touch on the Safari browser of iOS. Related Pr ...

Arranging extensive menu sections and content containment

I am currently working on enhancing my website's navigation by creating a mega menu. However, I am facing issues with the organization of the divs containing the ul content. In the fiddle linked below, you can see that "Africa", "Asia", and "Oceania" ...

The button on the master page is not able to be accessed when it is covered by a div tag on the Home page of an ASP.NET website

On my home page, I have a div tag containing a login form. In the master page, there is a signout button. After the user logs in, the text box and label used in the login form are hidden, and the signout button becomes visible. However, I am facing an issu ...

ensuring that the brief description on my thumbnail is consistently centered

I am facing an issue with aligning text consistently in the middle of thumbnails on my website. Regardless of whether the text spans 1, 2, or 3 lines, I want it to always be positioned inline with the center of the thumbnail. I have tried various methods s ...

Removing an element from an object using ng-model when its value is empty is a standard practice

Utilizing the $resource service to access and modify resources on my API has been a challenge. An issue arises when the ng-model-bound object's value is set to empty - the bound element is removed from the object. This results in the missing element ...

Having trouble concealing the logout button even after signing out with ng-show in angularjs

The code for displaying the logout button is as follows: <li class="dropdown" data-ng-if="userName"> <a href class="dropdown-toggle clear" data-toggle="dropdown" data-ng-show="userName"> </a> <!-- dropdown --> <u ...

Angular and JS do not have the functionality to toggle the split button

I have a question that seems similar to others I've seen, but I haven't found a solution yet. Can someone please review my code? In the component, I have {{$ctrl.init}} and {{$ctrl.people}} assigned. I am sure this assignment is correct because ...

Selenium - Struggling to locate elements that are undeniably present on the website

I started a fun side project to automate tasks on the website using Selenium to automatically complete all achievements. You can check out my code on GitHub: https://github.com/jasperan/pyfastfingers However, I've run into an issue with the login pa ...

How to Align an Icon to the Right Inside a Label Element with Bootstrap 4

I'm attempting to achieve this layout with the icon contained within a label element. Edited in Photoshop: https://i.sstatic.net/m3Fax.png Current layout: https://i.sstatic.net/XRjvH.png Below is the code snippet for that particular section < ...

What are some ways I can ensure that my personalized bootstrap navbar adjusts to different viewport sizes?

I've created a custom navbar that fits perfectly on a screen that is 1300 pixels wide by 700 pixels high. https://i.sstatic.net/nOm0c.png However, when the viewport size is reduced, the navbar elements become misaligned: https://i.sstatic.net/zBqpQ ...

Cease the act of sending submissions through JavaScript ajax requests

I need to prevent a form submission based on the result of an ajax request... Here is the code I attempted to implement: The chreg() function is supposed to return a boolean value from the ajax request, but it's not working! Javascript: function ch ...

Creating a responsive image using only CSS can greatly enhance the user experience on

I'm working on creating images that are responsive and fit into a square shape regardless of their original dimensions. For example: http://prntscr.com/87jey9 (apologies for the poor image quality, unable to upload images here due to limited reputati ...

How to reposition the Bootstrap navbar Logo from the left to the center

I am looking to change the ordering of Bootstrap 4 Navbar. Currently, the logo is on the left side, but I want it in the center with menus on both sides. Can someone help me with changing this order? Check out the current Navbar layout below: <nav c ...

HTML-Formatted Email Content

Similar Question: MailTo with HTML body I am looking to utilize JavaScript to send emails. I came across this helpful post: Sending emails with JavaScript. My goal is to include images, bold text, and color changes in the email content. Does anyone h ...

Creating a promise in an AngularJS factory function to perform an operation

When working within an Angular factory, I am tasked with creating a function that must return a promise. Once the promise is returned, additional functionality will be added. SPApp.factory('processing', ['$http', '$rootScope&a ...