Caroline Olivia Caroline Olivia - 2 months ago 28
ASP.NET (C#) Question

Only one checkbox checked in repeater

I have a repeater with 1 checkbox for every item. I want to only have one checked at a time.

The checkboxes is asp:checkbox, don't know if it makes any difference.
I tried with some jquery but it doesn't seem to work.

<asp:Repeater runat="server" DataSourceID="SqlDataSource1" ID="repeater1">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" Checked='<%# Eval("carousel_check")%>'/>
</ItemTemplate>
</asp:Repeater>


I have tried to give the checkbox a cssclass (checked_button) and then this script.

$(document).ready(function () {
$('.checked_button').change(function () {
if ($(this).is(':checked')) {
$('.radio-similar').not(this).removeAttr('checked');
};
});
});

Win Win
Answer

ASP.Net Checkbox is rendered inside span tag.

<span class="checked_button">
   <input id="MainContent_Repeater1_CheckBox1_2" 
     type="checkbox" name="ctl00$MainContent$Repeater1$ctl02$CheckBox1">
</span>

So the selector should be .checked_button input. Then uncheck all checkboxes, and check only the one triggered the click event.

$(function() {
    $(".checked_button input").click(function () {
        $('.checked_button input').attr("checked", false);
        $(this).prop("checked", true);
     });
});
Comments