开发者

Javascript tickbox validation

开发者 https://www.devze.com 2023-01-09 17:24 出处:网络
I am try开发者_如何学JAVAing to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes excep

I am try开发者_如何学JAVAing to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes except the three that were ticked.

How could I go about doing that?

Thanx in advance!


The following will disable the rest of the checkboxes if you select 3 of them, and also enable them once you uncheck one of the three selected..

$(':checkbox').click(
    function(){
        var selected = $(':checkbox:checked').length;
        if (selected == 3)
        {
            $(':checkbox:not(:checked)').attr('disabled',true);
        }
        else
        {
           $(':checkbox:not(:checked)').attr('disabled',false);
        }
    }
);

Live demo


Have on onclick handler that when a checkbox is clicked it ups a counter by one if it is unchecked it decreases the count. After raising the count, test to see if it is three. Then probably the easiest method is to either save the ids of the three checked boxes or save them in the previous step. Then change the click event to return true only if the ids match the saved ids. Sorry I don't have time right now to actually write up any code. Hopefully this will get you started.


jQuery

$("#container :checkbox").click(function(){
   if ($("#container :checkbox").length >= 3) {
     $("#container :checkbox").attr("disabled", "disabled");
   }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消