happysmile happysmile - 2 years ago 111
Javascript Question

how to make user select only one check box in a checkboxlist

i have an check boxlist with (6 items under it). and i have an search button. if user clicks Search button it gets all the result.
i am binding the items for checkboxlist using database in .cs file

but now if user selects a checkbox[item1] its gets selected
and he tries to select an 2 checkbox[item2] then firstselected checkbox[item1] should be unselected. only checkbox[item2] should be selected

condition 2:
now if user as selected checkbox1 [item1] it gets selected. and now if user again clicks on checkboxi[item1] then it should get deselected.

either you can provide me the solution in javascript or JQuery
any help would be great . looking forward for an solution
thank you

Answer Source

While I definitely agree with the consensus that radio buttons are the way to go for your described use-case, here is a little snipped of jquery that will cause checkboxes to behave like radio buttons. You simply need to add a "groupname" attribute to your checkbox tag.


<legend>Group 1 - radio button behavior</legend>
<input type="checkbox" groupname="group1" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group1" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group1" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group1" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group1" value="5" /> Checkbox 5<br />

<legend>Group 2 - radio button behavior</legend>
<input type="checkbox" groupname="group2" value="1" /> Checkbox 1<br />
<input type="checkbox" groupname="group2" value="2" /> Checkbox 2<br />
<input type="checkbox" groupname="group2" value="3" /> Checkbox 3<br />
<input type="checkbox" groupname="group2" value="4" /> Checkbox 4<br />
<input type="checkbox" groupname="group2" value="5" /> Checkbox 5<br />

<legend>Group 3 normal checkbox behavior</legend>
<input type="checkbox" value="1" /> Checkbox 1<br />
<input type="checkbox" value="2" /> Checkbox 2<br />
<input type="checkbox" value="3" /> Checkbox 3<br />
<input type="checkbox" value="4" /> Checkbox 4<br />
<input type="checkbox" value="5" /> Checkbox 5<br />


    <script type="text/javascript">
    $(document).ready(function() {
        $('input[type=checkbox]').click(function() {
        var groupName = $(this).attr('groupname');

            if (!groupName)

            var checked = $(this).is(':checked');

            $("input[groupname='" + groupName + "']:checked").each(function() {
                $(this).prop('checked', '');

            if (checked)
                $(this).prop('checked', 'checked');

I'm sure there are opportunities to increase brevity and performance, but this should get you started.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download