Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5622

JS checkbox enable/disable input

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

Upvotes: 0

Views: 559

Answers (7)

Nisarg
Nisarg

Reputation: 3282

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

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148704

You can use simple selector :

 $('input:checkbox').change(function(){
        $(this).nextUntil('br').prop('disabled', !this.checked)
    }).change();

Upvotes: 0

Sid M
Sid M

Reputation: 4364

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

Upvotes: 0

jeremija
jeremija

Reputation: 2538

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.

Upvotes: 0

Ringo
Ringo

Reputation: 3967

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

Upvotes: 0

kevpoccs
kevpoccs

Reputation: 635

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

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

Demo Corrected

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

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

Upvotes: 4

Related Questions