What is the process for implementing text box validation on a button click within a gridview in asp.net utilizing javascript?

How can I implement textbox blank validation on button click within a gridview using JavaScript? My gridview has multiple rows with 2 textboxes and a save button in each row. I need to validate the textboxes when their corresponding save button is clicked.

I have attempted to create the validation logic, but it currently only works for hardcoded textBox ids. How can I modify this code to apply to all rows of the gridview?

function gvValidate() {

var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
 if(grid!=null) 
  {
   var Inputs = grid.getElementsByTagName("input"); 
    for(i = 0; i < Inputs.length; i++) 
     {
      if(Inputs[i].type == 'text' ) 
       {
           if (Inputs[i].id.includes('TextBoxCTTermCode')) 
             {
                 if (Inputs[i].value == "") {
                     alert("Please enter a value, blank input is not allowed");
                     return false;
                 }

             }
             else if (Inputs[i].id.includes('TextBoxCTTermDesc')) {
                 if (Inputs[i].value == "") {
                     alert("Please enter a value, blank input is not allowed");
                     return false;
                 }
             }

      }
     }
     return true;
 }

}

 Protected Sub GridViewTaxInformation_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewTaxInformation.RowDataBound
    Try
        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim btnSave As Button = DirectCast(e.Row.FindControl("ButtonSave"), Button)
            btnSave.Attributes.Add("onclick", "return gvValidate()")
        End If
    Catch ex As Exception
        Common.WriteLog(ex.Message)
        Common.WriteLog((ex.StackTrace))
        Response.Redirect("..\Errors.aspx", False)
    End Try
End Sub

Answer №1

Finally, after much anticipation, I have found the solution to my problem! All it took was passing the index of the row in the gridview to a JavaScript function.

Take a look at the code below:

 function validateRow(rowIndex) {

var grid = document.getElementById('<%= GridViewCTInformation.ClientID %>');
 if(grid!=null) {
     var inputs = grid.rows[rowIndex + 1].getElementsByTagName("input"); 
    for(i = 0; i < inputs.length; i++) 
     {
      if(inputs[i].type == 'text' ) 
       {
                  if (inputs[i].value == "") {
                     alert("Please enter a value, leaving it blank is not allowed");
                     return false;
                 }

      }
     }
     return true;
 }

}

Protected Sub Gridview_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewCTInformation.RowDataBound
    Try
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim saveBtn As Button = DirectCast(e.Row.FindControl("ButtonCTInfoSave"), Button)
            btnSave.Attributes.Add("onclick", "return validateRow(" + e.Row.RowIndex.ToString() + ")")
        End If
    Catch errorMsg As Exception
        Common.WriteLog(errorMsg.Message)
        Common.WriteLog((errorMsg.StackTrace))
        Response.Redirect("..\Errors.aspx", False)
    End Try
End Sub

Answer №2

Instead of checking for the ID, focus on verifying empty values.


if(Inputs[i].type == 'text' ) 
{
    if (Inputs[i].value == "") {
        alert("Please enter a value, leaving it blank is not permitted");
        return false;
    }
}

Answer №3

  <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="the textbox you want to validate" ForeColor="Red"></asp:RequiredFieldValidator>

Give it a shot, it could be useful! You can utilize validation controls to ensure the accuracy of user inputs.

Answer №4

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("[id*=GridView1] [id*=lnkUpdate]").click(function () {
        //Locate the GridView Row using the LinkButton reference.
        var row = $(this).closest("tr");

        //Access the TextBox control.
        var txtName = row.find("[id*=txtName]");

        //Retrieve the DropDownList control.
        var ddlCountries = row.find("[id*=ddlCountries]");

        var message = "";

        //Check if the TextBox control is empty.
        if ($.trim(txtName.val()) == "") {
            message += "Please input Name.\n";
        }

        //Check if the DropDownList control has a selection.
        if (ddlCountries.val() == "") {
            message += "Please choose a Country.";
        }

        //Show error message if validation fails.
        if (message != "") {
            alert(message);
            return false;
        }
        return true;
    });
});
</script>

Feel free to utilize the provided code for Grid View Validation.

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

What is the best method for sending form data, specifically uploaded images, in Python Bottle with Ajax?

This form belongs to me <form method='post' enctype='multipart/form-data' id='uploadForm' name='formn'> <input type='file' value='' name='newfile'> <input type=&a ...

I am facing an issue with my Asp.net Application, as it is currently running on a server time zone that is 12 and a half hours behind

I am currently facing an issue with my Asp.net Application where it is using a server time zone that is 12 and a half hours behind Indian time. I have already attempted to solve this problem by utilizing methods such as GetDate function and DateTime.Now. ...

Guide to accessing a method from a separate file with the help of an event bus

I'm working on CreateEntryStepper.vue where I have a button that needs to call a function in CreateEntryStepperImageUpload.vue when pressed. I understand that event busses need to be used, but I am unsure about what exactly needs to be passed and how ...

"Divs are now linked and drag as one cohesive unit instead of

As I was experimenting with making images draggable and resizable, I encountered a small issue. When I attempted to drag two or more images, they would merge into one large draggable object instead of remaining separate. My goal was to make each image drag ...

File upload failed with the Easy Upload Adapter in ckeditor

I am experiencing an issue when trying to upload an image. Despite researching the error, I have not been able to find a solution that works. My code is written in Express.js with ejs and specifically relates to the addPost.ejs file. <!DOCTYPE html& ...

Encountered an issue with the Mongoose Schema method: The model method is not recognized as a

Here are two Mongoose model schemas that I am working with. The LabReport model includes an array that references the SoilLab model. Within the SoilLab model, there is a static method that was initially used to choose which fields to display when retrievin ...

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

Hidden Div on Google Maps no longer concealing

Since early December, the Google map on my site has been working perfectly. However, the other night, I noticed that the map now defaults to open when entering the site and cannot be closed. Strangely, all my Google maps are behaving this way even though n ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

When trying to log the parsed JSON, it unexpectedly returns undefined even though it appears to be in good

Everything was working fine until a couple of days ago. Let's consider this as my PHP script: echo json_encode(array('stat'=>'ok')); I am sending an AJAX request to this script: $.post(base_url+'line/finalize/', {t ...

I'm curious about utilizing jsviews in conjunction with jquery sortable

Check out my jsFiddle Example where I am using jsViews in conjunction with JQuery sortable. By default, the remove function works fine; however, when you change the order of items and then try to delete one, multiple items are removed. How can this issue ...

Getting data from an HTML file with AJAX

I have a JavaScript application where I am trying to retrieve an HTML file in order to template it. Currently, I am using the following method: var _$e = null; $.ajax({ type: "GET", url: "/static ...

Retrieving a basic array of strings from the server using Ember.js

Can a simple JSON array be retrieved from the server and used as a constant lookup table in an Ember application? I have a Rails controller that sends back a basic array of strings: [ "item one", "item two", "item three", ...]. I do not want these to be f ...

Optimize your website by caching static pages and content using Node.js

When it comes to caching static content using nodejs, there seem to be two main methods that can be utilized: The first method involves using nodejs and utilizing the following code: app.use(express.static(path.join(__dirname, 'public'), { max ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

When using the .after() method to add jQuery elements, keep in mind that they will not trigger any

Here is the snippet of code provided: <s:file name="upload" id="upload"></s:file> $('input[id^="upload"]').change(function(){ alert("aa"); $(this).after('<input type="file" name="upload_3" id="upload_3"/> ...

How can you create a sophisticated JavaScript object with an intricate design?

In my code, I frequently instantiate an object with the following structure: costs: { totalPerYear, totalEver, perMonth: { items: { depreciation, insurance, credit, inspection, ...

Are there any customizable actions available for the `yarn remove [package]` command, such as post-installation hooks?

I must execute a script following the completion of the following commands: yarn add [package] yarn remove [package] yarn upgrade [package] yarn install postinstall gets triggered after yarn add, yarn upgrade, and yarn install. However, it doesn't s ...

Unable to successfully import an external HTML file that contains a script tag

I am currently experiencing an issue with my index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <title>MyApp</title> <link rel="import" href="./common.html"> </head> <body> ...