Conditionally enable or disable button by comparing textbox values within a gridview using C# programming

Hey there! I'm currently diving into the world of JavaScript and C#. Feel free to correct me if you see any mistakes along the way.

Check out my gridview code snippet below:

<asp:GridView ID="GridView1" CssClass="table table-hover table-bordered" runat="server" AutoGenerateColumns="False" ShowFooter="True" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCommand="GridView1_RowCommand">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    <Columns>
        <asp:BoundField DataField="AvlQty" HeaderText="Available" ItemStyle-Width="35">
            <ItemStyle Width="35px"></ItemStyle>
        </asp:BoundField>

        <asp:TemplateField HeaderText="Qty" ItemStyle-Width="70">
            <ItemTemplate>                
                <asp:TextBox ID="TextBoxQty" onkeyup="Calculate(this)" CssClass="txtQty" runat="server" Text='<%# Eval("SelQty") %>' MaxLength="5" Width="45"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBoxQty" Display="Dynamic" ForeColor="Red" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
                <asp:regularexpressionvalidator ID="revAvailablePeriod" runat="server" ErrorMessage="Must be greater than 0" ForeColor="Red" controltovalidate="TextBoxQty" validationexpression="^[1-9][0-9]*(\.[0-9]+)?|0+\.[0-9]*[1-9][0-9]*$" setfocusonerror="true" validationgroup="AddAssests" xmlns:asp="#unknown"></asp:regularexpressionvalidator>
                <asp:CompareValidator ID="CompareValidator1" runat="server" ValueToCompare='<%# Eval("AvlQty") %>' ControlToValidate="TextBoxQty" ForeColor="Red" ErrorMessage="Must be less than Available" Operator="LessThan" Type="Integer"></asp:CompareValidator>
            </ItemTemplate>
            <ItemStyle Width="70px"></ItemStyle>
        </asp:TemplateField></Columns> 
</asp:GridView>

<asp:Button ID="Button2" runat="server" Enabled="false" Text="Place Order >>" CssClass="btn btn-info" OnClick="Button2_Click" />

If the quantity is greater than the available quantity for every row of the gridview, the button should be disabled. Otherwise, it should remain enabled.

Currently, I'm looking to implement this functionality using a JavaScript function. Would appreciate any help in achieving this task!

I've written a JavaScript function, but I'm not sure about when and how to call it. Here's what I have so far:

function Calculate() {
    var grid = document.getElementById("<%= GridView1.ClientID%>");
    var counter = 0;
    for (var i = 1; i < grid.rows.length; i++) {
        var txtAvl = grid.rows[i].cells[3];
        var qty = grid.rows[i].cells[5];
        if (txtAvl.value >= qty.value && qty.value > 0) {
            counter++;
        } else {
            document.getElementById('Button2').disabled = true;
        }
    }
    if (counter == grid.rows.length) {
        document.getElementById('Button2').disabled = false;
    }
}

Answer №1

Using the onkeyup event is sufficient to trigger this validation function written in JavaScript. I made some slight modifications to your script and it seems to be working smoothly now.

<script type="text/javascript>
        function CalculateValues() {
            var grid = document.getElementById('GridView1');
            var counter = 0;

            for (var i = 1; i < grid.rows.length; i++) {

                var txtQty = document.getElementById('GridView1_ctl0' + (i + 1) + '_TextBoxQty'); //Identifying TextBox element

                if (txtQty !== undefined) {

                    var qty = txtQty.value;
                    var txtAvl = grid.rows[i].cells[0].innerHTML;

                    if (txtAvl >= qty && qty > 0) {
                        counter++;
                    }
                    else {
                        document.getElementById('Button2').disabled = true;
                        break;
                    }
                }
            }

            if (counter === grid.rows.length - 2)
                document.getElementById('Button2').disabled = false;
        } 
    </script>

Make sure to adjust the IDs of the Gridview and TextBox elements accordingly in your code. Hopefully, this clarification helps.

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

"Extracting regular expressions between the penultimate and ultimate characters

I'm struggling with a simple regex question. I want to extract text between two specific characters: - and ~ Here's my string: Champions tour - To Win1 - To Win2 ~JIM FURYK Currently, when I use this regex pattern: \-([^)]+\~), it mat ...

Sort LINQ OrderBy with case-insensitive ASCII ordering

I need help sorting strings ("A", "_", "a") in C# using LINQ to adhere to ASCII order while disregarding case sensitivity. The relevant strings are: A = 65 _ = 95 a = 97 Expected output: A, _, a I've tried various StringComparer options but none ...

Using the createElement method in React to restart a GIF animation

In my React project, I'm attempting to develop a function that generates a new element displaying a gif for one loop before removing it. My current approach looks like this: function playGif() { var gif = document.createElement('img') ...

What is the best way to retrieve the chosen table row (tr) in this situation?

I have a table displayed below: How can I retrieve the selected mobile number of the tr when a button is clicked? <table class="table table-striped table-bordered table-hover table-full-width dataTable" id="sample_2" aria-describedby="sample_2_info"&g ...

The absence of transpiled Typescript code "*.js" in imports

Here is an example of the code I am working with: User.ts ... import { UserFavoriteRoom } from "./UserFavoriteRoom.js"; import { Room } from "./Room.js"; import { Reservation } from "./Reservation.js"; import { Message } from ...

How can I transform this in JavaScript so that it returns a Promise?

Currently, I am trying to implement code that I found in a SaaS's example. The goal is to retrieve the correct URL for a specific action. The sample code provided by the SaaS looks like this, but I would like to modify it so that it returns a Promise ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

The distinction between storing data and component data becomes apparent when using Vuex in conjunction with a persisted state

Below is my post.js file in the store directory: import axios from 'axios' import createPersistedState from "vuex-persistedstate" export default { namespaced: true, state: { sample_data: 'Welcome!!', l ...

How to save HTML content in a variable for future use in Next.js

When working with Next JS, my code resembles something like this: function Test() { return ( <section> <div>Test</div> </section> ); } Now, imagine that I want to have multiple entries here, gen ...

Do the "Save to Drive" buttons require manual cleaning?

Utilizing the Google Drive API for JavaScript within a VueJS application can be done as follows: In your index.html <script type="text/javascript"> window.___gcfg = { parsetags: 'explicit', lang: 'en-US' }; </scri ...

Extracting names from HTML can be done easily by looking for the "@" symbol that the

My HTML structure looks like this: <table id="table-15244" cellspacing="0" class="comment"><tbody> <tr id="comment-37"> <td style="color: #999" class="NV"> </td> <td class="hidden-mob"> ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

Replace the value of a variable when another variable becomes false in Angular.js

Currently, I am working on a project using Angular and have run into an issue that I need help with: In my project, I have two variables - signed which is a boolean bound to a checkbox, and grade which is an integer bound to a number input field. I am lo ...

Discover how to retrieve full response data by entering text into a text field using Reactjs

I am encountering an issue while retrieving values from rendered data in a component that has already been displayed on the page. I want to input data into a text field and have it sent to the database, but using the runtime data from that specific field. ...

Consolidate three different applications into a single one using asp.net mvc 3.0

I am currently working on three MVC3 web projects within a single solution - admin, UI, and service (WCF service). As I now need to host it on a single IP address using Network Solution, I am looking for suggestions on how to merge all these individual pr ...

How to override the styling of a parent element in CSS

I'm encountering an issue with my website's sidebar. I've set the background color to yellow for elements with the currentPage class. This works fine for the 'Home' tab, but when I try to do the same for a nested tab like 'tag ...

Managing duplicated data models names

While working on connecting to an extensive online service using JSON in C#, I've noticed that they use the same name with different values and types. This poses a challenge when creating JSON models as different models require different value types. ...

What is the best way to discover all available matches?

By utilizing this code snippet, I am able to locate text between specific start and end words. However, the search process stops after the first pair is found. Is there a way to identify all matches? const file = fs.readFileSync('./history.txt', ...

Issue with variable creation within ng-repeat

After reading a question on StackOverflow about determining the number of filtered out elements, I wrote the following code in Angular: <input type="text" ng-model="query" placeholder="Enter query..."> <div ng-if="filteredData.length!=data.length ...

Discrepancy found in C# Webbrowser control: the displayed content does not match the Document.inner

Currently, I am facing an issue with my website that is being loaded into the webbrowser control of my form. Despite loading the document successfully, when I try to retrieve the webbrowser.documenttext, I cannot seem to find a specific table that should b ...