sun
sun

Reputation: 1668

How to disable a textbox if a checkbox is checked using jQuery?

I want to disable a textbox if a user unchecks a checkbox and change the background colour of textbox. If the user checks the checkbox then that textbox should be editable and changes to white colour. Here is the code

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

Where .ba is the checkbox and .tex is textbox classes, now when the user clicks it changes to grey color but if they click again the color not changing.I want to see if the check box is checked if it is checked then nothing should happen else if the user uncheck the check box the textbox background color should change and it should go to non-editable that is disabled.Can anyone help?

I am using Below javascript to check all and uncheck all

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;
        }
    }
}

Is this causes any problem?

Upvotes: 5

Views: 17894

Answers (4)

user1823761
user1823761

Reputation:

Working jsFiddle Demo

Consider the following markup:

<input type="checkbox" class="ba" checked="checked" />
<input type="text" class="tex" />

And your JS:

$(function () {
    $('.ba').on('change', function () {
        var checked = $(this).prop('checked');
        $('.tex').prop('disabled', !checked);
    });
});

Upvotes: 6

GautamD31
GautamD31

Reputation: 28763

Try like

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

Upvotes: 1

himadri
himadri

Reputation: 638

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

Upvotes: 1

alexb
alexb

Reputation: 971

Here is JS the code

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

I recommend you to check out Jquery API. It's a fun read :)

Upvotes: 3

Related Questions