Disable all but one checkbox

帅比萌擦擦* 提交于 2019-12-23 04:34:35

问题


I saw this on jsfiddle and I wanted to know how I would alter it so that if and only if 45 is checked the rest are disabled, if if 45 is unselected then the rest are enabled. I should be able to do all this with out submitting the form.

The example javascript on jsfiddle:

$(function(){
    $(".rambo").change(function(){
        $(this).siblings().attr("disabled", $(this).is(":checked"));  
    });
});

回答1:


Just add proper ids and select on that

HTML:

<input type="checkbox" id="cb1" class="rambo" value='1' /> 45 
<input type="checkbox" id="cb2" class="rambo" value='2' /> 56 
<input type="checkbox" id="cb3" class="rambo" value='3' /> 56

JS:

$(function(){
    $("#cb1").change(function(){
        $(this).siblings().attr("disabled", $(this).is(":checked"));  
    });
});

JSFiddle




回答2:


You can use attribute selector.

$(function(){
    $(".rambo[value=1]").change(function(){
        $(this).siblings().prop("disabled", this.checked);  
    });
});

http://jsfiddle.net/Mnmte/




回答3:


Remove .rambo class from others.




回答4:


$(function(){
    $(".rambo").change(function(){
      if($(this).val() == 1){
        $(this).siblings().attr("disabled", $(this).is(":checked"));  
      }
    });
});

One way




回答5:


Above from all the answers, you can also specify that you only want the 1st checkbox to execute the script by using nth-child selector:

$(".rambo:nth-child(1)").change(function(){
    $(this).siblings().attr("disabled", $(this).is(":checked"));  
});

Demo



来源:https://stackoverflow.com/questions/14370119/disable-all-but-one-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!