The functionality to deactivate the Textbox when the Checkbox is checked is currently not functioning as expected

I wrote a script that disables textboxes whenever a checkbox is unchecked in a gridview:

$(function () {
    //Enable or disable all textboxes when header row checkbox is checked.
    $("[id*=chkHeader]").on("click", function () {
        var chkHeader = $(this);

        //Find and reference the GridView.
        var grid = $(this).closest("table");

        //Loop through the checkboxes in each row.
        $("td", grid).find("input[type=checkbox]").each(function () {

            //If the header checkbox is checked, then check all checkboxes and enable the textboxes.
            if (chkHeader.is(":checked")) {
                $(this).attr("checked", "checked");
                var td = $("td", $(this).closest("tr"));
                $("input[type=text]", td).removeAttr("disabled");
            } 
            else {
                $(this).removeAttr("checked");
                var td = $("td", $(this).closest("tr"));
                $("input[type=text]", td).attr("disabled", "disabled");
                $("input[type=text]", td).val("");
            }
        });
    });

    //Enable or disable textboxes in a row when the row checkbox is checked.
    $("[id*=chkResult]").on("click", function () {

        //Find and reference the GridView.
        var grid = $(this).closest("table");

        //Find and reference the Header Checkbox.
        var chkHeader = $("[id*=chkHeader]", grid);

        //If the checkbox is unchecked, then disable the textboxes in that row.
        if (!$(this).is(":checked")) {
            var td = $("td", $(this).closest("tr"));
            $("input[type=text]", td).attr("disabled", "disabled");
            $("input[type=text]", td).val("");
        } 
        else {
            var td = $("td", $(this).closest("tr"));
            $("input[type=text]", td).removeAttr("disabled");
        }

        //Enable the Header Row Checkbox if all the Row Checkboxes are checked and vice versa.
        if ($("[id*=chkResult]", grid).length == $("[id*=chkResult]:checked", grid).length) {
            chkHeader.attr("checked", "checked");
        } 
        else {
            chkHeader.removeAttr("checked");
        }
    });
});

The ASP code:

<table>
    <tr>
        <asp:Panel ID="pnlItems" runat="server" Height="100%">
           <td colspan="3" class="PrimaryLabelTop" style="height: auto" >
                <asp:Label ID="lbItems" runat="server" CssClass="PrimaryLabel" meta:resourcekey="lblNecropsyFoundResource1">
                    Necropsy: Itemized Information
                </asp:Label>
                <br />
                <br />
                <asp:GridView ID="gvItems" runat="server" EmptyDataText="No data available." Width="100%" DataSourceID="dsItems" EnableModelValidation="True" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="ValueID" HeaderText="ValueID" SortExpression="NecropsyValueID" InsertVisible="False" ReadOnly="True" Visible="false" />
                        <asp:BoundField DataField="GroupE" HeaderText="Group Description" SortExpression="GroupE" ReadOnly="true"/>
                        <asp:BoundField DataField="ItemE" HeaderText="Item Description" SortExpression="ItemE" ReadOnly="true"/>   
                        <asp:TemplateField HeaderStyle-Width="10%" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Center">
                            <HeaderTemplate>
                                <asp:CheckBox ID="chkHeader" runat="server"/>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <asp:CheckBox ID="chkResult" runat="server" Checked='<%# IIf(Eval("Result").ToString() = "Selected", True, False) %>' AutoPostBack="True"/>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Comment" SortExpression="Commment">
                            <ItemTemplate>
                                <asp:TextBox ID="txtComment" Visible='<%# Bind("AllowMemo")%>' runat="server" Text='<%# Bind("Comment") %>'></asp:TextBox>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="ValueID" HeaderText="ValueID" InsertVisible="False" ReadOnly="True" SortExpression="ValueID" Visible="false"/>
                    </Columns>
                </asp:GridView>
                <br />
                <asp:ObjectDataSource ID="dsItems" runat="server" SelectMethod="GetItemValues" TypeName="HealthWeb.HealthWS.Health">
                    <SelectParameters>
                        <asp:QueryStringParameter DefaultValue="0" Name="SampleID" QueryStringField="QS_LABSAMPLE" Type="Int32" />
                    </SelectParameters>
                </asp:ObjectDataSource>
            </td>
        </asp:Panel>
    </tr> 
    <tr>
        <td class="PrimaryLabelTop" />
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnSave" runat="server" Text="Save" meta:resourcekey="btnSaveResource1" height="26px" style="text-align: center" width="60px" />
            <asp:Button ID="btnClose" runat="server" Text="Close" meta:resourcekey="btnCloseResource1" height="26px" style="text-align: center" width="60px" />
        </td>
    </tr>
</table>

Issue 1: The [chkHeader] works correctly. However, when trying to individually check one [chkResult], it clears the [txtComment] but enables all txtComments instead of only the specific row I just checked.

Issue 2: How can I disable textboxes when a checkbox is unchecked from within the gridview?

Thank you!

Answer №1

By setting autopostback=true, the system will trigger a postback causing the loss of your value. To prevent this, manage the controls within the onRowDataBound method where you have the ability to configure each row's controls and properties accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are there any tools available in Jquery for generating a visual representation of an organizational hierarchy?

Currently, I am working on a genealogy project and searching for a suitable jQuery plugin to help me create a family tree. ...

The content of the webpage stays visible at all times, even when refreshed

Currently, I am in the process of learning Express and attempting to create a website similar to bit.ly's URL shortener. At this point, I have managed to display the links on the page successfully. However, when I refresh the page, the link remains vi ...

What is the best way to set up a React handler that can handle multiple values effectively?

Struggling with a handler that is not behaving as expected. I need to update the 'quantity' value of multiple items, but currently they all get updated with the last value entered. How can I change multiple values and update items individually? H ...

Changing the bootstrap popover location

I'm looking to customize the position of a Bootstrap popover that appears outside of a panel. Here's my setup: HTML: <div class="panel"> <div class="panel-body"> <input type="text" id="text_input" data-toggle="popover ...

Issue with this.setState() not updating value despite not being related to asynchronous updates

Just a quick note, this specific question does not involve any asynchronous update problem (at least, as far as I can tell). I currently have a class component with the following code snippet (simplified for clarity on the main issue): constructor(props ...

"Performing a MongoDB Node query within the time frame of 1 hour from

I am having trouble retrieving data with my query to find all objects within the last hour based on timestamps: Here is the schema I am using: var visitSchema = mongoose.Schema({ timestamp: { type: Date, default: Date.now }, userID: String, userName ...

The AJAX calendar control remains unchanged after a reset

I am currently facing an issue with my ajax calendar control used in a form for selecting dates. The problem arises when I select a date from the previous year and then click on the reset button. Even though the text box is cleared, the calendar control s ...

Is it necessary to incorporate iOS default controls into my HTML code?

Currently in the process of developing a cordova app, I am inclined to steer clear of default popups like the spinner triggered when selecting an item <select></select> (I plan on crafting my own dropdown tailored for mobile use). Additionally, ...

Filtering data in an antd table by searching

Just starting out with React hooks, specifically using TypeScript, and I'm struggling to implement a search filter with two parameters. Currently, the search filter is only working with one parameter which is 'receiver?.name?'. However, I wo ...

What could be causing the error message "Uncaught ReferenceError: userId is not defined" to appear for me?

Despite the fact that my alert($userId) is displaying 1 (which is the user id), I am still receiving an error indicating that userId is not defined. Any thoughts on why this might be happening? $('.postComment').on('click', function(ev ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

An AngularJS error has been caught: [$injector:modulerr]

After implementing AngularJS in my application, I encountered an error when adding a configuration section for routing: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.9/$injector/modulerr?p0=demoApp&p1=Error%3A…nts%2FGitHub%2FS ...

Ways to empty an angularJS array

let itemList = ['X', 'Y', 'Z']; Even though the array is cleared, the user interface does not reflect the change. itemList = []; This method solves the issue. But why? itemList.length = 0; ...

Learn the best way to efficiently transfer multiple checkbox selections in a single object using AJAX

In my form, I have 4 checkboxes with unique IDs like filter_AFFILIATION_1, filter_AFFILIATION_2, and so on up to 4. My goal is to dynamically send the values of checked checkboxes to the server using an ajax call. Below is the snippet of my code: $(&a ...

Tips for effectively integrating data from MongoDB into a React application

Currently, I am utilizing two components to extract data from the database. One component is used to loop through the data entries, while the second one is dedicated to accessing and displaying the details for each entry. Within my database, there is a fie ...

Refreshing Rails Views by Periodically Polling the Database

We are currently developing a statusboard to monitor all our external servers. Our database contains information about OS, software versions, and other details that are subject to frequent updates. To ensure real-time visibility of these changes on the web ...

Fetching a destination through the post approach

Typically, we utilize window.location.href="/index.php?querystring"; in JavaScript. Is it possible to transmit the querystring via a POST method without including any form within the document? ...

Adding ttf files to the content script of a Chrome extension

Currently, I am using a content script to inject some HTML into a webpage. My goal is to incorporate the google font named CabinCondensed-Regular, along with several icon fonts that I obtained from IcoMoon. I have already downloaded the necessary font file ...

Is it possible for Spring Boot to initiate an action that will dynamically update an image in an HTML document using JavaScript or another method?

I am currently facing a challenge in updating an image on a website built with HTML, while utilizing Spring Boot as the backend technology. As of now, I am using JavaScript to update the image at regular intervals, but the timing does not align with when t ...

Error: The function $rootScope.$on is not defined within the Connectivity Factory

I am facing an issue with my Ionic app while trying to run it in offline mode. The error message "services.js:392 Uncaught TypeError: $rootScope.$on is not a function" appears when I launch the app. Can someone please explain why this is happening and what ...