What is the best way to assign a class to a read-only field in HTML and CSS?

My situation is as follows: I have jQuery code that uses an if-statement to add a specific class to an element based on the selected value on a form page. I also created another form where users can view the details of a previously filled out form. However, when the details page is displayed, the gray "read-only" background overrides the background color from the original class. I don't want to delve into the bootstrap files to modify the read-only background color code if possible. How can I apply the complete class (including the background color) to a read-only element?

Code snippet from the "Create" page:

<div class="col-md-12">
                <div class="col-md-10">
                    @Html.LabelFor(model => model.Question1, htmlAttributes: new { @class = "control-label" })
                </div>
                <div class="col-md-2">
                    @Html.DropDownListFor(model => model.Question1, new[] { new SelectListItem() { Text = "Pass", Value = "Pass" }, new SelectListItem() { Text = "Fail", Value = "Fail" }, new SelectListItem() { Text = "NA", Value = "NA" } }, "Select an option", htmlAttributes: new { @class = "form-control text-box centerline", @onchange = "updateEscalationsListeningScore()", id = "question1Answer" })
                    @Html.ValidationMessageFor(model => model.Question1, "", new { @class = "text-danger" })
                </div>
            </div>

jQuery from the "Create" page:

if (Q1Answer === "Pass") {
        $('#question1Answer').addClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 3;
        Q1PotentialPoints = 3;
    }
    else if (Q1Answer === "Fail") {
        $('#question1Answer').addClass("incorrectListeningAnswer").removeClass("correctListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 0;
        Q1PotentialPoints = 3;
    }
    else if (Q1Answer === "NA") {
        $('#question1Answer').addClass("naListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("correctListeningAnswer");
        Q1Score = 0;
        Q1PotentialPoints = 0;
    }
    else {
        $('#question1Answer').removeClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 3;
        Q1PotentialPoints = 3;
    }

Code snippet from the "Details" page:

<div class="col-md-12">
                <div class="col-md-10">
                    @Html.LabelFor(model => model.Question1, htmlAttributes: new { @class = "control-label" })
                </div>
                <div class="col-md-2">
                    @Html.EditorFor(model => model.Question1, new { htmlAttributes = new { @class = "form-control text-box centerline", id = "question1Answer", @readonly = "readonly" } })
                    @Html.ValidationMessageFor(model => model.Question1, "", new { @class = "text-danger" })
                </div>
            </div>

jQuery from the "Details" page:

        if (Q1Answer === "Pass") {
        $('#question1Answer').addClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 3;
        Q1PotentialPoints = 3;
    }
    else if (Q1Answer === "Fail") {
        $('#question1Answer').addClass("incorrectListeningAnswer").removeClass("correctListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 0;
        Q1PotentialPoints = 3;
    }
    else if (Q1Answer === "NA") {
        $('#question1Answer').addClass("naListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("correctListeningAnswer");
        Q1Score = 0;
        Q1PotentialPoints = 0;
    }
    else {
        $('#question1Answer').removeClass("correctListeningAnswer").removeClass("incorrectListeningAnswer").removeClass("naListeningAnswer");
        Q1Score = 3;
        Q1PotentialPoints = 3;
    }

CSS

.correctListeningAnswer {
background-color: #c6efce;
color: #006100;}

.incorrectListeningAnswer {
background-color: #ffc7ce;
color: #9c0006;}

.naListeningAnswer {
background-color: #ffeb9c;
color: #9c5700;}

Many thanks for your assistance.

Cory

Answer №1

Big thanks to everyone for the valuable information! I took some time to explore the suggestions provided, and I managed to make it work. Surprisingly, the solution turned out to be quite simple, and I was able to achieve it by utilizing CBroe's method. All I had to do was incorporate the following code into my CSS file:

.correctListeningAnswer[readonly] {
background-color: #c6efce;
color: #006100;
}

.incorrectListeningAnswer[readonly] {
background-color: #ffc7ce;
color: #9c0006;
}

.naListeningAnswer[readonly] {
background-color: #ffeb9c;
color: #9c5700;
}

A big thank you to everyone for your assistance!

Answer №2

Instead of setting the field to readonly, consider using disabled instead. This way, your background will display correctly.

For instance, you can do the following:

input {
  background-color:#ffc;
}
<input type="text" disabled>

Alternatively, you could avoid using a form field altogether to present information. Extract the data from the initial form and display it using more appropriate elements such as span, which are not editable by default.

document.querySelector("button").addEventListener("click", function(){
  document.getElementById("dataOut").textContent = document.getElementById("dataIn").value;
});
<input id="dataIn">
<button type="button">Simulate a submit</button>
<span id="dataOut"></span>

If necessary, you can make your class selector more specific than the Bootstrap selectors to ensure that your styles take precedence over them.

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

What is the process for converting a string into a date while disregarding the time zone

Due to the way dates are stored, it is important for me to retrieve them exactly as they are stored, but time zones are causing issues. moment("2020-10-28T08:41:00.000Z").format("YYYY-MM-DD HH:mm") // Result: 2020-10-28 09:41 However, ...

I'm encountering errors from JQuery right from the start of the code

Hey there, I encountered a problem with my script: $(document).ready(function(){ alert("works"); }) I tried using a regular document.ready check but it keeps throwing 7 errors at me. Check out the screenshot of the errors here Any help or advice wo ...

Learning to implement $first in an Angular ng-repeat to dynamically add a new table row

I am currently facing an issue with displaying a Google map for addresses in my Angular application. The problem seems to be related to the asynchronous nature of HTML and JS, but I am struggling to find a solution. The issue is that even though the map vi ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Are there any conventional methods for modifying a map within an Aerospike list?

Attempting to modify an object in a list using this approach failed const { bins: data } = await client.get(key); // { array: [{ variable: 1 }, { variable: 2 }] } const { array } = await client.operate(key, [Aerospike.maps.put('array', 3).withCon ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

What is the best way to remove the background from a button that uses -moz

After adding the select component to my page, I noticed a problem with the select button in Firefox. In Chrome, the arrow down button looks normal, like this, but in Firefox it appears differently, as shown in this image. How can I remove the background ...

Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await fo ...

Guide to modifying Button on fetch response in React Native

After receiving a response from the server, I need to adjust the button based on the friends_status field in the following response: { "responseHeader": { "type": "314", "status": "200", "message": "Successfully found the profile" }, "ne ...

The alignment of flexbox within a list item is not positioned at the top as expected

When I place a flexbox inside a list item, the content is being pushed down by what seems to be a full line height. I have tried various CSS properties like setting margin-top: 0 for the flexbox, margin-top: 0 for its children, adding flex-wrap to the fle ...

I am seeking to perform these operations solely using pure WebGL, without relying on the Three.js library

if( keyboard.pressed("up")) pobjects[movementControls.translate].translateX(1); if( keyboard.pressed("down")) pobjects[movementControls.translate].translateX(-1); if( keyboard.pressed("left")) pobjects[mo ...

"Delving into the intricacies of Angular's factory

If I have a factory like the one below: app.factory("categoryFactory", function (api, $http, $q) { var selected = null; var categoryList = []; return { getList: function () { var d = $q.defer(); if(categoryL ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Submit field values only once the form has been confirmed to be validated

My current project involves using AJAX to submit form values, with the added requirement of implementing form validation. If any field in the form is empty, the submission should be prevented. I'm facing a challenge in figuring out how to halt the for ...

Problem with Layering in Javascript Canvas Game using Kinetic JS

Currently, I am attempting to replicate the game found at and delving into html5 canvas and kineticJS for my study. Here is the link to my fiddle: http://jsfiddle.net/2WRwY/7/ The issues I am facing are as follows: The tail part of the player in the f ...

In order to manage this file type properly, you might require a suitable loader, such as an arrow function within a React

Currently, I am in the process of creating an npm package and have encountered a difficulty with the following code: You may need an appropriate loader to handle this file type. | } | | holenNummerInSchnur = Schnur => { | if (this.beurte ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Integrate CSS and Javascript Plugins into your Ruby on Rails application

I am utilizing an HTML, CSS, and JS template to design the interface for my Rails application. Within this template, there are several plug-ins that are required in both CSS and JS formats. I have stored these plug-ins within the "/assets/plugins/" directo ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Tips for incorporating an HTML file using ng-include in double curly brace syntax {{ }}

Here is the code snippet I am working with: <div ng-repeat="pTabs in child.productTabs" ng-click="toggleProductTab($index)" ng-if="productTabIsActive(pTabs, $index)"> <div ng-repeat="specs in pTab.additionalSpecs"> <p>{{spec ...