Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

javascript - How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group. One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.

In my case, I have many checkbox groups on the same page, so I want it to work like this example. An asp.net codebehind example is here, but I want to do it in client side code.

How can I do this in JavaScript?

i have decided to use the ajax mutually exclusive checkbox extender. The solutions given so far are basically based on radio buttons. This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows

HTML

<div>    
    Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
    Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
    Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>

<div>
    Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
    Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
    Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>

Jquery

$('div .checkbox').click(function () { 
                 checkedState = $(this).attr('checked');
                  $(this).parent('div').children('.checkbox:checked').each(function () {
                      $(this).attr('checked', false);
                  });
                  $(this).attr('checked', checkedState);
});

And here is fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...