Javascript Gridview checkbox alert message not working properly.

Gani_tpt 1,806 Reputation points
2024-05-19T14:52:29.7566667+00:00

I am using javascript validation in gridview.

I have selected checkboxes in the gridview. but, still it's throwing alert message unncessarily.

where is the problem in the below code.

kindly update asap if anyone identified the issues.

or pls. provide some server side javascript validation for the same.

Note : i am unable to debugg javascript in vs 2019.

  <script type="text/javascript">
        var TargetBaseControl = null;

        window.onload = function () {
            try {
                //get target base control.
                TargetBaseControl =
                    document.getElementById('<%= this.gvcustomer.ClientID %>');             }
            catch (err) {
                TargetBaseControl = null;
            }
        }

        function Validate_Checkbox() {
            if (TargetBaseControl == null) return false;

            //get target child control.
            var TargetChildControl = "CheckBox1";

            //get all the control of the type INPUT in the base control.
            var Inputs = TargetBaseControl.getElementsByTagName("input");

            for (var n = 0; n < Inputs.length; ++n)
                if (Inputs[n].type == 'checkbox' &&
                    Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
                    Inputs[n].checked)
                    return true;

            alert('Select at least one checkbox!');
            return false;
        }
    </script>

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,330 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,422 questions
0 comments No comments
{count} votes

Accepted answer
  1. Lan Huang-MSFT 26,761 Reputation points Microsoft Vendor
    2024-05-20T09:54:14.3866667+00:00

    Hi @Gani_tpt,

    You cannot use JavaScript to get all checkboxes in a paginated GridView, JavaScript can only view the current page.You can try on the server side, for example:

     protected void btnCheck_Click(object sender, EventArgs e)
     {
         int a = gvCustomer.PageIndex;
         int counter = 0;
         //Loop through All Pages
         for (int i = 0; i < gvCustomer.PageCount; i++)
         {
             //Set Page Index
             gvCustomer.SetPageIndex(i);
             //After Setting Page Index Loop through its Rows
             int totalCount = gvCustomer.Rows.Cast<GridViewRow>().Count(r => ((CheckBox)r.FindControl("CheckBox1")).Checked);
             counter= counter + totalCount;
         }
         if (counter == 0)
         {
             ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Select at least one checkbox!')", true);
         }
         gvCustomer.SetPageIndex(a);
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 58,356 Reputation points
    2024-05-19T15:53:37.7233333+00:00

    The browser contain a debugger. View source and check the checkboxs id are what is expected.


  2. Albert Kallal 4,971 Reputation points
    2024-05-19T20:17:07.3666667+00:00

    Assuming we are continuing from the last post?

    We can't really use JavaScript here, since we have a paged GridView, and the JavaScript can only see and look at the current page.

    Hence, if other pages of the GridView have checked box, then JavaScript that "just" checks the current GridView page will not suffice here.

    Of course, we could change the previous design of our code, and not use a post-back, but when the text (or check box) is change, we could call a webmethod and use some "ajax" for the GridView.

    However, since we have all the moving parts wired up and working?

    Then best to check for no checked rows WHEN the user hits the save button.

    Hence, assume I go to page 3, enter some comments, but forget to check the box. In fact, we kind of don't need the check box, and we could assume that if no comments been entered, then the user not done anything with any row of the GridView. However, for now, the design is that the user is to enter comments, and check the box. So, in theory, we don't need the check box, or in fact if the user enters some comments, then we could automatic check the box. So, consider this for the future.

    So, all we have to do is add some code to the save button, and check if now rows have a checked = true.

    The code looks like this:

            protected void cmdSave_Click(object sender, EventArgs e)
            {
                // always send current grid page back to rstData
                GridToTable();
    
                // make sure user checked at least one hotel
    
                DataRow[] drChecker = rstData.Select("[Checked] = 1");
    
                if (drChecker.Length == 0)
                {
                    string sJava = "alert('you must select at least one row')";
                    ScriptManager.RegisterStartupScript(Page, 
                                Page.GetType(), "popit",sJava, true);
    
                    return;
                }
    
                // now send table back to database with updates
                string strSQL = "SELECT * from tblHotels";
                using (SqlCommand cmdSQL = new SqlCommand(strSQL,
                                            new SqlConnection(Properties.Settings.Default.TEST4)))
                {
                    cmdSQL.Connection.Open();
                    SqlDataAdapter daupdate = new SqlDataAdapter(cmdSQL);
                    SqlCommandBuilder cmdBuild = new SqlCommandBuilder(daupdate);
    
                    daupdate.Update(rstData);
                }
            }
    
    

    And the result is this:

    savepage2

    So, you can't really use "just" JavaScript to check if a row been checked, since you have a pager for the GridView, and your JavaScript can only see the current rows on the current page, but with a pager, then you have many pages.

    As noted, one could introduce a web method, but for now, since we have a server side save button, then that is the best point in time to test and check for no rows having been checked.