简体   繁体   中英

checkbox select/deselect in repeater when click on text

say we have simple asp.net repeater, in a row we have one checkbox, one label (database-id of the record) and not visible (used for postback) and one text (in a tabelcell)

now i want to make it like in windows, if you click on the text, the checkbox should be selected or deselected.

has somebody a link or solution for this, maybe already with jQuery?

Edit: as i said, it is a asp.repeater. and the table is for layout, so using the checkbox.text property is not designable (eg line wrap) the ids of the checkbox and text are dynamically added/changed on rendering of the repeater. therefore the label solution does also not really work.

assume that you wont't need jQuery and the table-construct

<asp:Repeater runat="server">
    <ItemTemplate>
        <asp:CheckBox runat="server" Text="your text" />
    </ItemTemplate>
</asp:Repeater>

this renders basically the solution provided by Ricardo Vega whatever you get in the property text of the checkbox is clickable, and checks/unchecks the checkbox ... therefor you should use <%# Eval("...") %> you can skin (via css) the margin of the label

After thinking about this once again, there is another solution:

<asp:Repeater runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td><asp:Checkbox runat="server" ID="checkbox" /></td>
            <td><asp:Label runat="server" AssociatedControlID="checkbox">Your text</asp:Label></td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

Notes: You can use the Text-attribute of the asp:Label-Element either!

maybe I don't understand completely but why don't you use the html attribute "for" in the label tag?

Like:

<label for="field_id">Checkbox 1</label>
<input id="field_id" type="checkbox" />

And that will make the checkbox act as clicked if the label is clicked. So you don't have to depende on JS to do this.

Edit: If you really really want to use jQuery for this:

$('td').click(function(){
  $(':checkbox',this).attr('checked',!$(':checkbox',this).attr('checked'));
});

Change 'td' as needed.

If you go with one of the jQuery click solutions make sure you ignore click events triggered by the checkbox itself.

$('td').click(function(e){
    if (!$(e.target).is(':checkbox')) { // toggle only on non-checkbox click
        var checked = $(':checkbox', this).attr('checked');
        $(':checkbox', this).attr('checked', !checked); // toggle
    }
});

How about something like this?

$('.yourtableclass td').click( function( e ) {
    var cb = $(this).children('input[type=checkbox]').get(0);
    cb.checked = !cb.checked;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM