user2928264
user2928264

Reputation: 21

Checkbox OnCheckedChanged not firing when checkbox is checked through JQuery

I used this code to be able to check the checkbox on gridview row select which is working. However, the code behind is not being run unless I click the actual checkbox. Any ideas?

ASPX Code:

<asp:GridView runat="server" ID="gvReconciledGroups" AutoGenerateColumns="false" EmptyDataText="No Reconciled Items to Batch" DataKeyNames="GroupID">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="cbFinalise" AutoPostBack="true" OnCheckedChanged="cbFinalise_OnCheckedChanged" ClientIDMode="Static" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="GroupID" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" DataField="GroupID" />
        <asp:BoundField HeaderText="Date" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" DataField="Date" DataFormatString="{0:dd/MM/yyyy}" ItemStyle-Width="100px" />
        <asp:BoundField HeaderText="Cashier" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" DataField="Cashier" ItemStyle-Width="100px" />

Script:

<script type="text/javascript">
    $(function () {
        $('tr.gridview_row,tr.gridview_alternatingRow').click(function () {
            var checked = $(this).find('input[id*=cbFinalise]').prop('checked');
            $(this).find('input[id*=cbFinalise]').prop('checked', !checked);
        });
    });
</script>

Code Behind:

public void cbFinalise_OnCheckedChanged(Object sender, EventArgs e)
{
    //Calculations
}

Upvotes: 0

Views: 2279

Answers (2)

Samuel Caillerie
Samuel Caillerie

Reputation: 8275

I suggest you to trigger a click on your checkbox in order to force the postback :

<script type="text/javascript">
   $(function () {
       $('tr.gridview_row,tr.gridview_alternatingRow').click(function () {
           $(this).find('input[id*=cbFinalise]').trigger('click');
       });
   });
</script>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337570

jQuery is entirely client side. OnCheckedChanged will only fire on the server side after a postback has happened due to the radio input being clicked on. Try this:

$('tr.gridview_row,tr.gridview_alternatingRow').click(function () {
    $(this).find('input[id*=cbFinalise]').click(); // this should force a postback
});

Note that manually changing the checked property of the control is redundant as you will be refreshing the page anyway and the state of the control will be set by ASP.Net as it re-renders the page.

Upvotes: 1

Related Questions