Ensuring the accuracy of multiple input fields using a unified JavaScript function

Can you help me with a JavaScript code to validate 7 textboxes as Required fields when a button named Update is clicked? I am new to JS and the code I have tried so far is not working properly.

function fnCheck(val) {
    var v = val.id.split('_')[1];
    var merter = document.getElementById('GridSubMeter_' + v + '_txtMeterIdn').value.trim();
    var Billper = document.getElementById('GridSubMeter_' + v + '_txBillPer').value.trim()
    var Endkwh = document.getElementById('GridSubMeter_' + v + '_txEndKwh').value.trim();
    var startkwh = document.getElementById('GridSubMeter_' + v + '_txStartKwh').value.trim();
    var ReadEndDate = document.getElementById('GridSubMeter_' + v + '_txReadEndDate').value.trim();
    var ReadStartDate = document.getElementById('GridSubMeter_' + v + '_txReadStartDate').value.trim();
    var CTFACT = document.getElementById('GridSubMeter_' + v + '_txCTFact').value.trim();
    
    if (merter === '' || Billper === '' || Endkwh === '' || startkwh === '' || ReadEndDate === '' || ReadStartDate === '' || CTFACT === '') {
        alert("Please fill in all required fields");
        return false;
    } else {
        return true;
    }
}
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="fnCheck(this);" Text="Update" CommandName="Update" />

Answer №1

Check out the following solution:

<asp:TemplateField HeaderText="">
      <ItemTemplate>
          <asp:TextBox ID="Textbox1" runat="server"></asp:TextBox>
           <asp:RequiredFieldValidator ID="validator" runat="server" ControlToValidate="Textbox1" ValidationGroup="gridview" ErrorMessage="This field is required"></asp:RequiredFieldValidator>
       </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
            <ItemTemplate>
                <asp:Button ID="BtnSubmit" runat="server" Text="Submit" ValidationGroup="gridview" CausesValidation="true" />
            </ItemTemplate>
        </asp:TemplateField>

This code snippet was sourced from here.

I have tested this on a sample project and it should work for your specific situation.

Answer №2

Hey Deepak,

Here is the Gridview code that I have:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="DataKeyId" DataSourceID="SqlDataSource1" EnableModelValidation="True">
            <Columns>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="gridview" CausesValidation="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv11" runat="server" ControlToValidate="TextBox1" ValidationGroup="gridview" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="TextBox2" ValidationGroup="gridview" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv3" runat="server" ControlToValidate="TextBox3" ValidationGroup="gridview" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv4" runat="server" ControlToValidate="TextBox4" ValidationGroup="gridview" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>                    
            </Columns>
        </asp:GridView>

After clicking on the button within the GridView, the following error is displayed:

https://i.sstatic.net/59fAH.png

Answer №3

Here is an alternative version to display error messages at the row level:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="YourDataKey" DataSourceID="SqlDataSource1" EnableModelValidation="True">
            <Columns>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup = '<%# "Group_" + Container.DataItemIndex %>' CausesValidation="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="TextBox1" ValidationGroup = '<%# "Group_" + Container.DataItemIndex %>'  ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv2" runat="server" ControlToValidate="TextBox2" ValidationGroup = '<%# "Group_" + Container.DataItemIndex %>'  ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv3" runat="server" ControlToValidate="TextBox3" ValidationGroup = '<%# "Group_" + Container.DataItemIndex %>' ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="rfv4" runat="server" ControlToValidate="TextBox4" ValidationGroup = '<%# "Group_" + Container.DataItemIndex %>' ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
                    </ItemTemplate>
                </asp:TemplateField>                    
            </Columns>
        </asp:GridView>

The third row button has been clicked in the screenshot below, and the second column has a value. This results in errors appearing for the remaining controls of that row.

https://i.sstatic.net/5exHD.png

Answer №4

After working on my JavaScript function, I am pleased to say that it is now functioning as expected. I have implemented a variable success which acts as a flag, and I check it multiple times before returning true at the end. This ensures that if one textbox is empty while another is not, the function will not return true. Please excuse any editing errors in my code.

function fnCheck(val) {
        var success = true;
        var v = val.id.split('_')[1];
        var merter = document.getElementById('GridSubMeter_' + v + '_txtMeterIdn').value.trim();
        var Billper = document.getElementById('GridSubMeter_' + v + '_txBillPer').value.trim()
        var Endkwh = document.getElementById('GridSubMeter_' + v + '_txEndKwh').value.trim();
        var startkwh = document.getElementById('GridSubMeter_' + v + '_txStartKwh').value.trim();
        var ReadEndDate = document.getElementById('GridSubMeter_' + v + '_txReadEndDate').value.trim();
        var ReadStartDate = document.getElementById('GridSubMeter_' + v + '_txReadStartDate').value.trim();
        var CTFACT = document.getElementById('GridSubMeter_' + v + '_txCTFact').value.trim();
        debugger;
        if (merter != '') {

        }
        else {
            alert("Meter Identifier is Required Field");
            success = false;
        }

        // Rest of the validation checks
        // ...

        return success;

    }

onclientclick

<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px"  CausesValidation="false" runat="server"  OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />

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

Regular expression that detects a phone number which does not consist of a repetition of the same digit throughout

Looking for a regex pattern to match phone numbers that do not consist of the same number repeated throughout every part. Specifically, I need it to target 10-digit phone numbers in the format (123)123-1234. I have tried using this pattern, but it's ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

AngularJS: ng-repeat excluding duplicate keys

Here is a collection of objects I am working with: [{ key:test1 name: name1 }, { key:test1 name: name2 }, { key:test2 name: name3 }] I am currently using ng-repeat to showcase them: <tr ng-repeat=item in list> <td>{{item.key}}</td ...

Ways to showcase every resource from an API in React JS

I need help with adding code to display products along with their images from an API in my existing code. Can someone assist me with this? import React, {useState, useEffect} from 'react' import "bootstrap/dist/css/bootstrap.min.css" im ...

"The function within the Sails.js model is not properly returning a value when rendered

Within my Sails.js application, I am currently attempting to retrieve the total number of users that have been approved in my database and utilize this count variable within my view by employing the count() query. Below is the snippet of code present in my ...

Prevent Camera from Rotating Outside of Set Time Frame

In my current VR game project using THREE.js, I am attempting to constrain the camera rotation on the y-axis within specific angles to prevent users from seeing behind them. Instead, they should only be able to look left and right. Although I am uncertain ...

What is the best way to implement restful instead of query syntax in a $resource factory?

Recently, I set up a $resource factory like this: (function() { 'use strict'; app.factory('WidgetFactory', [ '$resource', function($resource) { return $resource('http://localhost:8282/widget/:widgetId&apo ...

Instructions for passing the chosen value to Django

I am struggling to set up a search button using Ajax and Django. I need to send the selected value to the server, but I can't seem to retrieve the value from the select HTML tag. The variable value always ends up empty ({"obj":""}). Any ideas? HTML : ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Automatically update local library dependencies with npm

Utilizing the local package dependency functionality of npm, I have implemented it in the following manner: npm install --save "file:/path/to/module" After updating my library module by running npm run build to generate dist files, I then execut ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Extracting information from JSON structure

My JSON object response includes a `series` array of objects structured like this: { series: [ { name: 'a', data: [1,2,3] }, { name: 'b', data: [4,5,6] } ] } I am looking to extract the `data` values th ...

As soon as I hit the submit button on my website form, the URL is automatically refreshed with the information I provided

I am a beginner when it comes to forms and recently copied and pasted this login snippet code: <div class="login-form-1"> <form id="login-form" class="text-left"> <div class="main-login-form"> <div class="login-group"> ...

The rendering of React child components is not functioning

Hi there! I am new to using React and I am currently facing an issue with rendering components. My problem is that only the parent component is being displayed, and the child components are not being recognized by React. Here is the snippet of code from m ...

Is it possible to execute JavaScript within an Android application?

Is there a way to utilize the javascript provided by a website on an Android device to extract and analyze the emitted information? Here is the javascript code: <script type="text/javascript" src="http://pulllist.comixology.com/js/pulllist/5b467b28e73 ...

Possible revision: "Exploring ways to iterate through an array of objects in Node/Express and verify if a corresponding entry exists in a MongoDB

Working on building a web application using the MEAN stack and Yelp API to retrieve an array of objects representing local businesses. I manipulate this data on the front-end, but before sending a response, I need to verify if a specific object exists in m ...

Is there a way for me to generate a custom subtype of Error that can be thrown?

I am attempting to create my own custom error in order to handle it differently when catching it. I want to be able to call if(instanceof DatabaseError) and execute my specific handling logic. export class DatabaseError extends Error { constructor(...a ...

The monorepo contains TypeScript files with a .js extension, causing confusion for IDEs that are unable to recognize TypeScript code within them

After cloning the React monorepo from GitHub and opening it as a new project in WebStorm IDE, I encountered an issue. It turns out that all the .js files in this repository are actually written in TypeScript, causing confusion for the IDE. For instance: / ...

Changing Color of Specific Sticky Note in React - Customize Color of Individual Note Without Affecting Others

In React, I am working on a basic application for sticky notes that allows users to create as many of them as they'd like. One issue I'm facing is with changing the color of individual sticky notes – currently, when I change the color, it affe ...