views:

64

answers:

3

I have listview with two checkboxes in itemtemplate. I want to validate that user can only select only one checkbox in each row.

+2  A: 

The behaviour you're describing is accomplished using standard HTML radiobuttons. If you change your design to use these you'll get the benefit that

  1. The user can only select a single item, no extra javascript needed
  2. Users expect to be able to choose multiple checkboxes but only a single radiobutton IE you're working with their expectations

If you're still sure you want to use jQuery then something like this should do it.

$(':checkbox').change(function(){
    if($(this).attr('checked')) {
        $(this).siblings(':checkbox').attr('checked',false);
    }
});
Evil Andy
yes i want to use javascript or jquery to do this.
vinit
cannot use radiobuttons as I am doing something like user can select All option for either of the two check boxes or he can select individual checkbox but he cannot select both the options at a time.Its purpose is it send either mail or sms to end users from list.
vinit
+1 for using the right tool for the job.
David Thomas
A: 

Thanks for the reply. had also asked one of my friend and he gave me the following solution which is working fine. Posting it, if anybody needs it.-

say ur checkboxes in the 2 clumns are named EmailCheckBox and SMSCheckBox

then use this code to toggle the checkboxes in each single row:

$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox); $('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);

        function uncheckOthercheckbox() {

            if (this.id.indexOf("EmailCheckBox") != -1) {

                var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
            }
            else {

                var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
            }

            var i = "#" + otherCheckBoxId;
            if (this.checked) {

                $(i).removeAttr('checked');
            }                

        }
vinit
A: 

@vinit, just a little change, you forgot the else part,

$('input:checkbox[id*=EmailCheckBox]').click(uncheckOthercheckbox);
$('input:checkbox[id*=SMSCheckBox]').click(uncheckOthercheckbox);

        function uncheckOthercheckbox() {

            if (this.id.indexOf("EmailCheckBox") != -1) {

                var otherCheckBoxId = this.id.substring(0, this.id.indexOf("EmailCheckBox")) + "SMSCheckBox";
            }
            else {

                var otherCheckBoxId = this.id.substring(0, this.id.indexOf("SMSCheckBox")) + "EmailCheckBox";
            }

            var i = "#" + otherCheckBoxId;
            if (this.checked) {

                $(i).removeAttr('checked');
            }
            else {

                if ($(i).attr('checked') === false) {
                    $(i).attr('checked', 'checked');
                }
            }

        }
nash