Using jQuery to dynamically disable a textbox when a checkbox is checked

I'm trying to implement a functionality where a textbox becomes disabled and changes its background color when a user unchecks a checkbox. Conversely, if the user checks the checkbox, the textbox should become editable and change its background color to white. Below is the code snippet:

$(document).ready(function () {
    $(".ba").click(function () {
        $(".tex").css("background-color", "#CCCCCC");
    });
});

In this code, .ba represents the checkbox class, and .tex represents the textbox class. Currently, when the user clicks the checkbox, the color changes to grey, but clicking again doesn't revert it back. I want the color to change only when the checkbox is unchecked, making the textbox non-editable. Can anyone assist with this?

I'm also using the following JavaScript function to handle checking all and unchecking all checkboxes:

function checkAll(formname, checktoggle) {
    var checkboxes = new Array(); 
    checkboxes = document[formname].getElementsByTagName('input');

    for (var i=0; i<checkboxes.length; i++)  {
        if (checkboxes[i].type == 'checkbox')   {
            checkboxes[i].checked = checktoggle;
        }
    }
}

Could this be causing any issues in the implementation? Any insights would be appreciated.

Answer №1

Interactive jsFiddle Example

Take a look at this HTML structure:

<input type="checkbox" class="active" checked="checked" />
<input type="text" class="input-field" />

Here is the relevant JavaScript code:

$(function () {
    $('.active').on('change', function () {
        var isChecked = $(this).prop('checked');
        $('.input-field').prop('disabled', !isChecked);
    });
});

Answer №2

Take a look at this JavaScript code snippet

$(".ba").click(function () {
    if ($(".ba").is(":checked")) {
        $(".tex")
            .removeAttr("disabled")
            .css("background-color", "white");
    }
    else {
        $(".tex")
            .attr("disabled", "disabled")
            .css("background-color", "red");
    }
});

I highly recommend exploring the Jquery API. It's an interesting resource to delve into :)

Answer №3

$(document).ready(function(){
$(".ba").click(function() {
if ($('#check_id').is(":checked"))
{
  $(".tex").css("background-color","#CCCCCC");
}
else
{
   $(".tex").css("background-color","#DDDDDD");
}
});
});

Answer №4

Experiment with

$(".ba").on('click',function() {
   if($(this).is(':checked'))
       $(".tex").css("background-color","#CCCCCC");
   else
       $('.tex').prop('disabled', false);
})'

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 method can I use to locate the double quote option within an HTML select element using jQuery?

Here is an example of the select: <select id="id0" name="name0"> <option value='30" size'> 30" size </option> </select> The select contains double quotes. I am trying ...

Utilizing jQuery to apply a class to a targeted element when clicked

I'm currently working on animating a menu item where it expands to the left when hovered over, and contracts back when the mouse moves out. This part is functioning as expected. Additionally, I am trying to apply a specific color to the button by add ...

Unable to display button image when using both id and style class in CSS

During my transition from Java 7 to Java 8, I've encountered a peculiar issue. Here's a brief explanation: In my FXML file, I have a button defined with style class button-red-big and id btnInput: <Button id="btnInput" fx:id="btnInput" align ...

What are the best practices for implementing jquery owlCarousel within an Angular 4 component?

I've included my 'carousel.js' file like this: $('#owl-carousel-1').owlCarousel({...}); and in carousel.component.html, I have: <div id="owl-carousel-1" class="owl-carousel owl-theme center-owl-nav home- carousel">....< ...

Creating a platform akin to YouTube for sharing videos online

Currently, I am in the process of creating a personalized website that bears similarities to YouTube. However, I am unsure about how to enable new pages and files on this platform. Despite being relatively new to HTML, I possess a basic understanding of co ...

Script to Trigger Download Button

I'm having trouble with a rar file download on my website (ravens-hangar.tk). A bunch of lines of script keep popping up. Can anyone help me out? Thanks in advance! .download { width: 120px; height: 30px; font-size: 20px; text-align: center ...

Combining the jquery-UI slider functionality with the canvas rotate() method

Is there a way to rotate an image using html2canvas plugin and jQuery UI slider? I am new to programming and need some guidance on how to achieve this feature. Here is my current progress: http://jsfiddle.net/davadi/3d3wbpt7/3/ ` $("#slider").slider({ ...

Retrieve an item from the Ionic Firebase database

My current challenge is retrieving data from the Firebase database. user-service.ts getProfile(){ try {; return this.afDatabse.object(`profile/${this.afAuth.auth.currentUser.uid}`); } catch (e) { console.log(e); } } c ...

Pure CSS navigation - radio buttons to display or hide different pages

I'm attempting to create a website navigation bar using radio buttons, where the pages are displayed based on the selection. So far, I've managed to achieve this using <a href='#div'></a> and a :target, by placing the .page ...

The JSON/jquery call to the second div yields an undefined error

When I fetch a row of data from a MySQL server using PHP, I then encode it into a JSON array. After that, I try to display the information by using the provided PHP script. However, I encountered a strange issue where if I send "vname" to its own div, I ...

Store the result of the previous AJAX call in a jQuery variable and combine it with the data from the next AJAX response

I am working on a program where I retrieve price values using ajax. My goal is to add the previous price value to the current price value when it is retrieved again. The issue I am facing is that each time I get a new price value, it overrides the previou ...

What specific quirk in Firefox is responsible for this behavior, and is there a way to replicate it in standards mode?

In Firefox, this particular document displays differently in standards mode compared to quirks mode. When in quirks mode, the div fills the entire screen, but in standards mode it does not. I went through the MDN quirks list and couldn't pinpoint a sp ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Failure to update content with new text in Ajax when GET/POST variables are included

I've been following a tutorial on Ajax functionality, and I have set up my code exactly like mmtuts. However, the new value isn't displaying until I make an adjustment to my test.js file: The original code that is not functioning as expected: $ ...

Using the jQuery dialog class selector with the each function

Having an issue with opening jQuery dialogs when clicking on buttons. Everything works fine when I have just one button and dialog, but things get complicated when dynamically creating multiple pairs of dialogs and buttons using a PHP loop. I tried using t ...

Would it be possible to use a script to convert the y-axis values of the chart into Arabic numerals?

Currently, I am working on creating line and pie charts, but I need the Y-axis to display Arabic language. $('button').on('click', function(e) { $('#pie-chart3').empty(); var type = $(this).d ...

The error message raised is "b.delegate is not a valid function"

By utilizing the jQuery shake effect, I need to include two jQuery files in my project. Below is the code snippet that allows a div element to shake: var isShaking = false; $(document).ready(function() { setInterval(function() { if (!isShakin ...

Leveraging jQuery for Sending Form Data to an ASP.NET ASMX Web Service

I am working on creating a straightforward login form where the submit button will post form data to a method in an asmx file. Unfortunately, I encounter an error whenever I try to post from inside a form tag. Posting outside of the form tags functions ...

How come the data in the datatable does not appear sorted as it was retrieved from the ajax response?

I am successfully able to load the Datatable using ajax. However, I am facing an issue where the table does not display the data in the same order as it is received. The data is fetched from report_ajax.php [json] {"data":[ ["22:00:00" ...

Move the scroll bar away from the scrollable div and reposition it on a different part of the page using CSS

Is it possible to use CSS to position the scrollbar of a div that takes up the left half of my page with overflow-y: scroll to be where the page scrollbar would normally be (far right side of the page)? I've experimented with the ::-webkit-scrollbar ...