Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

OnClick

Posted on 2007-11-15
10
Medium Priority
?
8,688 Views
Last Modified: 2008-02-21
I am trying to do a validation using onclick. However, it seems there is something problem. Page does not post to a different page once I added Attributes.Add("onclick", ...

Basically, I am trying to validate at least 1 checkbox selected from a DataGrid template column and proceed to post to a different page if validation pass.
<script language="javascript" type="text/javascript">
    function validateAtLeast1Checkbox()
    {
        var objForm = document.forms[0];
        var atLeast1Checked=false;
        
        // only adjacent counters to be enabled for same row
        for (i=0; i<objForm.elements.length; i++)
        {
            // checkbox and not itself
            if (objForm.elements[i].type=="checkbox" &&
                objForm.elements[i].id.indexOf('chkSelection') >= 0)
            {
                if (objForm.elements[i].checked)
                {
                    atLeast1Checked = true;
                    break;
                }
            }
        }
        
        if (!atLeast1Checked)
        {
            alert('No users are selected');
            return false;
        }
    }
    </script>
 
////
 
                <asp:Button ID="btnReset" runat="server" CssClass="button" Text="Reset Password"
                    EnableViewState="False" OnClick="btnReset_Click" PostBackUrl="~/admin/resetBatchPwd.aspx" />
 
////
 
    protected void Page_Load(object sender, EventArgs e)
    {
        this.btnReset.Attributes.Add("onclick", "return validateAtLeast1Checkbox();");
    }
 
///
    protected void btnReset_Click(object sender, EventArgs e)
    {
        // TODO: Validate at least one checked before submit
 
        string accountIDs = GetSelectedAccountID();
        this.hdnAccountIDs.Value = accountIDs;
    }

Open in new window

0
Comment
Question by:ee_guest
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 6

Expert Comment

by:ventaur
ID: 20291796
I highly recommend that you use a CustomValidator instead of the current approach. Remove the Attributes.Add("onclick", ...) code from the Page Load event handler and try the following instead.

Also, add a couple of parameters to your JS function to handle the validity check.
<asp:CustomValidator ID="cvAtLeastOneCheckBox" runat="server" Display="None" ClientValidationFunction="validateAtLeast1Checkbox" />
 
----------------
 
<script language="javascript" type="text/javascript">
function validateAtLeast1Checkbox(sender, args)
{
	var objForm = document.forms[0];
	var atLeast1Checked=false;
	
	// only adjacent counters to be enabled for same row
	for (i=0; i<objForm.elements.length; i++)
	{
		// checkbox and not itself
		if (objForm.elements[i].type=="checkbox" &&
			objForm.elements[i].id.indexOf('chkSelection') >= 0)
		{
			if (objForm.elements[i].checked)
			{
				atLeast1Checked = true;
				break;
			}
		}
	}
	
	if (!atLeast1Checked)
	{
		alert('No users are selected');
		args.IsValid = false;
	}
	else
		args.IsValid = true;
}
</script>

Open in new window

0
 
LVL 40

Expert Comment

by:evilrix
ID: 20292049
0
 

Author Comment

by:ee_guest
ID: 20298224
But I will still need the onclick event at the server side.

    private string GetSelectedAccountID()
    {
        string accountIDs = "";

        foreach (DataGridItem dgItem in dgSearch.Items)
        {
            CheckBox chkSelection = (CheckBox)dgItem.FindControl("chkSelection");
            if (chkSelection.Checked)
            {
                accountIDs += (dgItem.FindControl("lblAccountID") as Label).Text + ",";
            }
        }

        if (accountIDs != "")
            accountIDs = accountIDs.Remove(accountIDs.Length - 1, 1);

        return accountIDs;
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        // TODO: Validate at least one checked before submit
 
        string accountIDs = GetSelectedAccountID();
        this.hdnAccountIDs.Value = accountIDs;
    }

It seems that lblAccountID is not visible when I do a HTML view source from IE. How come? But definitely it is visible at server side.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:ee_guest
ID: 20298251
I tried both using asp:Label and asp:TextBox in my datagrid but hide the column. The elements are not showing in my HTML view source if I hide the column.
0
 
LVL 6

Expert Comment

by:ventaur
ID: 20298324
I'm not sure I follow what you mean by trying "both using asp:Label and asp:TextBox". I thought you were validating a column of check boxes. If you hide a column in a grid, it will not show up in the HTML output at all.

You can keep the OnClick for the button, but will need to wrap the code for that event handler in an "if" statement that checks that the page is valid (see below).
protected void btnReset_Click(object sender, EventArgs e)
{
  if (Page.IsValid) {
    string accountIDs = GetSelectedAccountID();
    this.hdnAccountIDs.Value = accountIDs;
  }
}

Open in new window

0
 

Author Comment

by:ee_guest
ID: 20298548
It seems like the click event is skipped.
It did not go in at all.

    protected void btnReset_Click(object sender, EventArgs e)
    {
        // TODO: Validate at least one checked before submit
 
        if (Page.IsValid)
        {
            Response.Write("EEE");
            Response.End();
            string accountIDs = GetSelectedAccountID();
            this.hdnAccountIDs.Value = accountIDs;
        }
    }

Open in new window

0
 

Author Comment

by:ee_guest
ID: 20298644
FYI, I have more than 1 submit button and only the custom validation should only be enabled for one button. How to do that?
0
 
LVL 6

Accepted Solution

by:
ventaur earned 600 total points
ID: 20298663
My apologies. I forgot about the PostBackUrl being set on that button.

Yes, the OnClick code for that button will not execute on that page, because it posts directly to the "~/admin/resetBatchPwd.aspx" page. Your code will have to be moved to the Page_Load event handler of the other page, including the GetSelectedAccountID function.

Be sure you've read up on cross-page posting so you know how to access the controls of the PreviousPage.
0
 
LVL 6

Expert Comment

by:ventaur
ID: 20298687
If you are using ASP.NET v2.0, then you can set the ValidationGroup property of both the CustomValidator and the Button to the same value; for example, ValidationGroup="UsersGrid".
0
 

Author Comment

by:ee_guest
ID: 20298753
Excellent!
0

Featured Post

Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
Suggested Courses

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question