简体   繁体   中英

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

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

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

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

Demo Corrected

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

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.

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

You can use simple selector :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM