"Use jquery to disable and gray out a text box, restricting it to read-only

Is there a way to change the color of a text box to grey and make it read-only when a checkbox is ticked? I have managed to make the text box read-only, but I can't figure out how to also turn it grey. Using the disabled attribute won't work in this case because I still need the value of the text box to be sent, so that option is not available.

jQuery(document).ready(function () {
   $("#redflag2").click(function () {
      $('#new_contracted_support_hours').attr("readonly", $(this).is(":checked"));
      $('#new_contracted_support_hours').addclass("greyba", $(this).is(":checked"));
  });
});

css

.greyba{
    background-color:rgba(178,178,178,1.00);

}

Answer №1

Make sure to use addClass() instead of addclass() in order for the class to be added successfully.

For setting properties, it is recommended to use .prop(), and for toggling classes, use toggleClass().

Since jQuery 1.6, the .prop() method is used for explicit retrieval of property values, while .attr() retrieves attributes.

jQuery(document).ready(function () {
    $("#redflag2").change(function () {   
        $('#new_contracted_support_hours')
            .prop("readonly", this.checked)
            .toggleClass("greyba", this.checked);
    });
});

For more information, check out this comparison between .prop() and .attr()

Answer №2

jQuery(document).ready(function () {
   $("#redflag2").click(function () {
      $('#new_contracted_support_hours').prop("readonly", $(this).is(":checked"));
      if($(this).is(":checked")){
         $('#new_contracted_support_hours').addClass("greyba");
      }
   });

$("#redflag2").click(function () {
$('#new_contracted_support_hours').prop("readonly", $(this).is(":checked"));
if ($(this).is(":checked")) {
    $('#new_contracted_support_hours').addClass("greyba");
}
else{
    $('#new_contracted_support_hours').removeClass("greyba");
}
});
.greyba{
    background-color:rgba(178,178,178,1.00);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="new_contracted_support_hours" type="text"></input>
<input id="redflag2" type="checkbox"></input>

Answer №3

Have you considered clearly separating your concerns, using JS for functionality and CSS for styling? Utilizing the readonly attribute means minimal styling is needed in your JavaScript code.

Note: This implementation is just a demonstration

function toggleState(){
  document.getElementById('field').readOnly = document.getElementById('checkbox').checked;
}
$('#checkbox').on('change', toggleState); // toggle state on checkbox change
toggleState(); // toggle state on initial load
#field[readonly] {
  background: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="checkbox" type="checkbox" />
<input id="field" type="text" value="value.." />

Answer №4

<input type="text" id="audience" name=""/>

To set the readonly attribute, you can do the following:

$('#audience').attr('readonly', true);
$('#audience').css('background-color' , '#DEDEDE'); 

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

setting the width of <input> fields to automatically adjust

Curious about CSS. I was under the impression that setting width:auto for a display:block element would make it 'fill available space'. However, when applied to an <input> element, this doesn't seem to hold true. For instance: <b ...

jQuery issue - Error encountered: unable to load XRegExp multiple times within one frame

Clicking on a button triggers an AJAX call to one of my pages, which includes jqplot elements. The first click on the button works fine in terms of the AJAX request and response. However, when I attempt a second click on the button, an exception is throw ...

Output information to the specified divID using Response.Write

Currently, I have knowledge of javascript and I am currently expanding my skills in ASP.NET C#. My goal is to achieve the following task using javascript: document.getElementById('divID-1').innerHTML= '<p>Wrong Password< ...

send the variable to the deferred done function

Having trouble passing a variable into a done callback. var getDataForCompany = function(company_id) { $.ajax({ type: "post", url: url, data:{ company_id: company_id } }).done(function(returnedData, textStatus, j ...

Close the menu located in the menu bar under the Home section

I am struggling with creating the bootstrap collapse menu. <div className='collapse' id='mobile-menu'> <button clasNames='navbar-toggler' type='button' data-togg ...

Why is my custom function failing to operate on an array?

My function is created to organize and remove duplicates from a provided array. Below is an excerpt of the code: Bubble Sort - function organize(postsCollection, type, direction){ let target = postsCollection[0][type]; let swapp = false, ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...

What is the best way to utilize the fetch API in order to retrieve multiple variables from PHP?

I am attempting to retrieve more than one variable from my remote PHP using the JavaScript fetch API, here is my PHP code: <?php include 'config.php'; //$email = $_GET['email']; try { $dbh = new PDO("mysql:host=$dbhost;dbname= ...

Upon executing `$('div')`, an empty array is returned

My goal is to retrieve all the div classes on a page using jQuery $('div');. However, the page does not natively support jQuery, so I am loading it through external links until $ === jQuery evaluates to true. Even on Stack Overflow where jQuery ...

Is it possible for JavaScript to detect elements or scripts within a hidden element using display="none"?

Is it possible for scripts to locate elements that have been hidden in the DOM by setting their attribute to display="none"? ...

Tips for dynamically swapping out a texture image on a 3D model in three.js using Maya runtime

This website is currently loading a Maya model using the three.js library. The model includes various texture pictures. Below is the JavaScript code: var SCREEN_WIDTH = window.innerWidth; var SCREEN_HEIGHT = window.innerHeight; var container; var c ...

The container holding the inner elements is slightly oversized by a couple of pixels

Check out this Plunker example. Hello everyone, I am currently working on fitting two inner divs (a title bar and a canvas) inside an outer div. These inner divs are generated dynamically and have specific fixed dimensions. Below is a sample code snippet ...

What are the steps to collapse React state in a comments section?

Here is the data I have: { "currentUser": { "image": { "png": "/src/assets/images/avatars/image-juliusomo.png", "webp": "/src/assets/images/avatars/image-juliusomo.webp" }, ...

What is the best way to verify multiple email addresses simultaneously?

Is there a method to validate multiple email addresses entered by users in a textarea? My current approach involves using ng-pattern for validation. ...

Optimizing Performance with RequireJS Cache

We are currently experiencing an issue with RequireJS where it is not fetching a new version every time it is requested. We have attempted to address this by using the code below, but unfortunately, it has not solved the problem: require.config({ urlA ...

Troubleshooting Issue with Pull to Refresh and setState in React Native

Implementing Pull to refresh in a React Native App Currently, I am facing an issue with setting the state "refreshing" to true before fetching from the API. This results in a maximum update error being thrown. export default class NotificationScreen ex ...

In HTML, favoring the use of "//domain.com" over "https://domain.com" or "http://domain.com" is recommended for greater flexibility and compatibility

Related Questions: Changing all links to // Network-Path Reference URI / Scheme relative URLs I have noticed some websites using the following format: background:url(//cdn.domain.com/images/bg-normal.png) They utilize "//", which the browser aut ...

Incorporating information into Observable in Angular 2

I'm currently working on loading gifs from the API based on a search parameter in batches of 20. Once I reach the bottom of the page, I need to load another 20. To achieve this, I've implemented observables. However, I'm facing an issue with ...

Activate the checkbox input by defining the form type with Javascript

I am attempting to control the enabling or disabling of input types based on whether a checkbox is checked or unchecked using JavaScript. Here is the code I am using: <script language="JavaScript"> <!-- function enable_text(status) { status=!st ...

Is jQuery not displaying either HTML or working with $.ajax?

<form method="post" action="#" name="sign-up" id="sign-up"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <label for="last-name">Last Name:</label> <input type="text" id="last-name" name="l ...