0

Q: How to enable/disable input with checkbox?

Each checkbox enable/disable input next to it. Number of groups is various (i = 1,2,3, ...n). Default setting is that inputs are disabled and checkbox unchecked.

JsFiddle: http://jsfiddle.net/tDCB9/

HTML:

<input type="checkbox" name="group1" value="">
<input type="text" name="name11" class="stat" value="">
<input type="text" name="name12" class="stat" value="">
<input type="text" name="name13" class="stat" value="">

JS:

$("input[name="group1"][type="checkbox"]").click(function() {
    $("input[name="name11"][type="text"]").attr("disabled", !this.checked);
    $("input[name="name12"][type="text"]").attr("disabled", !this.checked);
    $("input[name="name13"][type="text"]").attr("disabled", !this.checked);
});
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
Ing. Michal Hudak
  • 5,338
  • 11
  • 60
  • 91

7 Answers7

4

You need to write a change() handler for the checkboxes and then use nextUntil() to find out the input fields to be disabled

$('input[type="checkbox"]').change(function(){
    $(this).nextUntil(':not(input:text)').prop('disabled', !this.checked)
}).change()

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

your code works, it's just a question of simple quote / double quote,

$("input[name='group1'][type='checkbox']")

Demo Corrected

kevpoccs
  • 635
  • 5
  • 8
0

Try this:

$("input[name='group1'][type='checkbox']").click(function() {
    if($(this).prop('checked')){
        $("input[name='name11'][type='text']").attr("disabled", 'disabled');
    }
    else{
        $("input[name='name11'][type='text']").removeAttr("disabled");
    }
});
Ringo
  • 3,795
  • 3
  • 22
  • 37
0

Here is a working fiddle.

$('input[type="checkbox"]').click(function() {
    $(this).siblings('input').attr('disabled', this.checked);
});

You just need to separate the input groups in a container.

jeremija
  • 2,338
  • 1
  • 20
  • 28
0

Try this

$("input[name='group1'][type='checkbox']").click(function() {
    $("input[name='name11'][type='text']").attr("disabled", !this.checked);
    $("input[name='name12'][type='text']").attr("disabled", !this.checked);
    $("input[name='name13'][type='text']").attr("disabled", !this.checked);
});
Sid M
  • 4,354
  • 4
  • 30
  • 50
0

You can use simple selector :

 $('input:checkbox').change(function(){
        $(this).nextUntil('br').prop('disabled', !this.checked)
    }).change();
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

Try This

$("input[name='group1'][type='checkbox']").click(function() {   
$("input[name='name11'][type='text']").attr("disabled", this.checked);
$("input[name='name12'][type='text']").attr("disabled", this.checked);
$("input[name='name13'][type='text']").attr("disabled", this.checked);
});
Nisarg
  • 3,024
  • 5
  • 32
  • 54