JavaScript Error: Issue detecting two distinct GridView checkboxes

In my web application (asp.net & vb code), I encountered an issue involving two different gridviews. Each gridview had checkboxes to select records for batch update, along with corresponding buttons for batch update actions.

A validation was required to ensure that users had checked checkboxes before clicking the corresponding batch update button.

My code was working fine and able to display an error message if no checkbox was checked before clicking the batch update button. However, I discovered an error in the functionality. For example, when I checked a checkbox in gridview2 and then clicked the batch update button for gridview1, no error message was shown. It seems that my JavaScript was unable to identify the checkbox associated with another gridview.

Here is my JavaScript code:

function IsSelectedAtleastOneOT() {
    var loTable1 = document.all("<%=Gridview1.ClientID%>"); // GridView Name        
    count1 = 0;
    with (document.forms[0]) {
        for (var i = 0; i < elements.length; i++) {
            var e1 = elements[i];
e.id.substring(e.id.lastIndexOf('_') + 1, e.id.length) == 'ControlName') // This is our control Name
              if (e1.type == "checkbox" && e1.checked == true) // This is our control Name
            {
                count1 += 1;
            }
        }
    }
    if (count1 == 0) {
        alert("You have not selected any record.");
        return false;
    }
    return true;
}

function IsSelectedAtleastOneActualDur() {
    var loTable2 = document.all("<%=Gridview2.ClientID%>"); // GridView Name
    count2 = 0;
    with (document.forms[0]) {
        for (var i = 0; i < elements.length; i++) {
            var e2 = elements[i];
            if (e2.type == "checkbox" && e2.checked == true ) 
            {
                count2 += 1;
            }
        }
    }
    if (count2 == 0) {
        alert("You have not select any record.");
        return false;
    }
    return true;
}

and the ASP.net code:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize ="10" AutoGenerateColumns="False"
    CellSpacing="1" DataSourceID="SqlDataSource1" CellPadding="2" 
    AllowSorting="True" DataKeyNames="ot_key" >
    <Columns>
         <asp:TemplateField>

 <ItemTemplate>
 <asp:CheckBox ID="chkSelect" runat="server"   />
 </ItemTemplate>
  </asp:TemplateField>

        <asp:HyperLinkField DataNavigateUrlFields="action,ot_key" DataNavigateUrlFormatString="{0}?id={1}"
            DataTextField="post_code" HeaderText="Staff" SortExpression="post_code" meta:resourcekey="GridView1_post_code"/>
    .......

    </Columns>
    <EmptyDataTemplate>
        <span style="font-size: 14pt; color: #990000">
        <asp:Localize runat="server" ID="text_no_record" Text="No records found." meta:resourcekey="text_no_record" />
        </span>
    </EmptyDataTemplate>
</asp:GridView>

<asp:Button ID="btnBatchUpdate" runat="server" Text="Batch Recommend/Approve Overtime Work"  
          OnClick="btnBatchUpdate_Click" 
          OnClientClick="return IsSelectedAtleastOneOT();" Visible="false" 
    Width="277px" meta:resourcekey="btnBatchUpdate" />

<asp:GridView ID="GridView2" runat="server" AllowPaging="True" AutoGenerateColumns="False"
    CellSpacing="1" DataSourceID="SqlDataSource3" CellPadding="2" AllowSorting="True" DataKeyNames="actual_dur_key"  PageSize ="10">
    <Columns>
         <asp:TemplateField>

 <ItemTemplate>
 <asp:CheckBox ID="chkSelectActual_dur" runat="server" />
 </ItemTemplate>
  </asp:TemplateField>

        <asp:HyperLinkField DataNavigateUrlFields="action,actual_dur_key" DataNavigateUrlFormatString="{0}?id={1}"
            DataTextField="post_code" HeaderText="Staff" SortExpression="post_code" meta:resourcekey="GridView2_post_code"/>
.....

    </Columns>
    <EmptyDataTemplate>
        <span style="font-size: 14pt; color: #990000">
        <asp:Localize runat="server" ID="text_no_record" Text="No records found." meta:resourcekey="text_no_record" />
        </span>
    </EmptyDataTemplate>
</asp:GridView>       

<asp:Button ID="btnBatchUpdateActualDur" runat="server" Text="Batch Recommend/Approve Actual Duration"  
          OnClick="btnBatchUpdateActualDur_Click" 
          OnClientClick="return IsSelectedAtleastOneActualDur();" 
    Visible="false" Width="276px" meta:resourcekey="btnBatchUpdateActualDur"/>

Answer №1

It seems that you are looking to validate both grid views when clicking on both batch buttons. To achieve this, you can either combine the two JavaScript functions into one or create a new function that checks both functions and returns a valid result, as shown below:

function CheckIfBothSelected()
{
     if(CheckIfOneSelected() && CheckIfBothSelected())
        return true;
     else
        return false;
}

For both buttons, assign the same onClientClick function as CheckIfBothSelected()

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

Creating effective href anchors within an iframe using the `srcdoc` attribute

While loading some HTML content in an iframe using the srcdoc attribute, I encountered an issue where following anchor tag links inside the iframe caused the entire page to load within the iframe instead of scrolling to the linked id. You can see a demons ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Javascript Code for toggling the visibility of a panel

I need help with a JavaScript code that can show or hide a panel depending on the data in a grid. If the grid has data, the panel should be displayed, but if the grid is empty, the panel should be hidden. I attempted to use the following code, but it did ...

Modify the button's border color upon click action

I am looking to implement a feature where the border of a button changes when clicked once and reverts back when clicked again. This should apply individually to each of the 16 buttons with the same class. Additionally, I want to enable the ability to clic ...

Switchable radio options

Currently, I am creating a form containing multiple options that are mutually exclusive. However, none of these options are mandatory. That is why I want to enable the user to uncheck a selected radio button by simply clicking on it again. This way, all th ...

Attempting to modify the audio tag's src attribute with JavaScript

I've been doing online research for the past few weeks and have come across similar solutions to what I'm trying to achieve. However, due to my limited knowledge of javascript, I am struggling to implement them effectively. My goal is to have an ...

Using the onMessage event in React Native WebView does not seem to have any functionality

I'm having trouble with the onMessage listener in React Native's WebView. The website is sending a postMessage (window.postMessage("Post message from web");) but for some reason, the onMessage listener is not working properly. I can't figure ...

I am curious about the distinction between two closures

Can someone please explain the distinction between these two closure examples? (function(window, undefined) { // JavaScript code })(window); Here's another example: (function(window) { // JavaScript code })(window, undefined); ...

Enhance your security with Ember-simple-auth when using ember-cli-simple-auth-token

Currently, I am in the process of utilizing ember-simple-auth alongside ember-cli-simple-auth-token: "ember-cli-simple-auth-token": "^0.7.3", "ember-simple-auth": "1.0.1" Below are my configurations: ENV['simple-auth-token'] = { authoriz ...

API requests seem to be failing on the server side, yet they are functioning properly when made through the browser

My current project involves utilizing an API that provides detailed information about countries. I've set up an express server to handle requests to this API, but for some reason it's not making the request. Interestingly, when I directly access ...

Is there a way to send a variable from a client-side script to a server-side script?

I am facing a challenge in Google App Maker where I am attempting to execute a Client Script to retrieve a variable and then pass that variable to a Server Script for further use. However, I am struggling to figure out the correct implementation. Within m ...

The path specified as "react-native/scripts/libraries" does not exist in the file

I've been troubleshooting an error on Github - https://github.com/callstack/react-native-fbads/issues/286. After cloning the repository and running it, I discovered that the error persisted. I am currently updating packages to investigate why this rec ...

Using Node.js, is there a way to divide an object's array property by 100 and then store each portion in individual files?

Looking to break down a large object into chunks of 100 and save each chunk in separate files using Node.js. However, struggling to figure out how to split an array with thousands of records into files of 100. Query: How can I divide an object's arr ...

Encountered a 404 error while trying to install body-parser

Hey there, I'm new to this and ran into an issue while trying to install the body-parser package. Can you please guide me on how to resolve this problem? D:\Calculator>npm install body-paeser npm ERR! code E404 npm ERR! 404 Not Found - GET htt ...

EJS selectively displaying certain elements from an object

This particular issue has been baffling me. I have been passing an object into an ejs template and when I output that object, everything appears as expected: { _id: 5504a5e7ff67ac473dd7655c, code: 'GB', name: 'United Kingdom', slug: & ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

When working with create-react-app and TypeScript, you may encounter an error stating: "JSX expressions in 'file_name.tsx' must

After setting up a React project with TypeScript using the CLI command create-react-app client --typescript, I encountered a compilation error when running npm start: ./src/App.js Line 26:13: 'React' must be in scope when using JSX react/r ...

Comparing v-show(true/false) and replaceWith: Exploring the best practice between Vue and jQuery

Currently, I am in the process of learning vue.js and have a question regarding the best approach to implement the following scenario: https://i.sstatic.net/2YBEF.png https://i.sstatic.net/YCEHG.png The main query is whether it is acceptable in HTML to w ...

Is it possible to access the Windows certificate store using JavaScript?

Is there a way to access the Windows certificate store using JavaScript? I'm looking to create a web application that can validate user logins by reading their certificates. ...