Solved

ASP.NET,Javascript: Compare values in a user control

Posted on 2008-10-02
22
1,009 Views
Last Modified: 2013-11-07
Hi I have the following user control but I failed compare values in the two text boxes. Can some one help?
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TextBoxcompareDate.ascx.cs" Inherits="TextBoxcompareDate" %>

<%@ Register TagPrefix="Date" Namespace="userControls" Assembly="TextBoxDate" %>
 

<head >

    <title>Untitled Page</title>

    <script language="javascript" type="text/javascript">
 

function validateDates(source, arguements)

{

    var thevalue = arguements.Value;

    

    arguements.IsValid=false;    

    

    if(!validateDate(thevalue))

    {

        alert(source.errormessage);

        return;

    }

    arguements.IsValid=true;  

            

}

function compareStartEnd()

{ 

    if(document.getElementById('<%=txtStart.ClientID%>').value > document.getElementById('<%=txtEnd.ClientID%>').value)

    {

        alert('The end date must be greather than the start date');

//        document.getElementById('<%=txtEnd.ClientID%>').focus();

    } 

}   

    </script>

</head>

<table width="100%">

    <tr>

        <td align="right" width="75%">

            <asp:Label ID="lblCaption" runat="server" Text="Title: " Font-Names="Verdana" Font-Size="10px" ForeColor="#000000"></asp:Label>

        </td>

        <td align="left" width="10%">

            <asp:TextBox 

                ID="txtStart" 

                runat="server" 

                MaxLength="10" 

                Width="80px"             

                style="padding: 2px;border:solid 1px #92C86A;background-color: #ffffff;font-family:Verdana;font-size: 11px;color:#000000;"

                onfocus="this.select();"></asp:TextBox>

         </td>

         <td align="center" width="5%">

            <span style="font-family:Verdana;font-size: 10px;font-weight:bold;color:#000000;">-</span>	        

         </td>

         <td align="left" width="10%">

            <asp:TextBox 

                ID="txtEnd" 

                runat="server" 

                MaxLength="10" 

                Width="80px" 

                style="padding: 2px;border:solid 1px #92C86A;background-color: #ffffff;font-family:Verdana;font-size: 11px;color:#000000;" 

                onfocus="this.select();" 

                onchange="compareStartEnd();" ></asp:TextBox>

        </td>            

    </tr>            

</table>

<asp:CustomValidator 

    ID="cuvStart" 

    runat="server" 

    ControlToValidate="txtStart" 

    ClientValidationFunction="validateDates" 

    ErrorMessage="Incorrect starting date." 

    SetFocusOnError="true"

    Display="None">&nbsp</asp:CustomValidator>

<asp:CustomValidator 

    ID="cuvEnd" 

    runat="server" 

    ControlToValidate="txtEnd" 

    ClientValidationFunction="validateDates" 

    ErrorMessage="Incorrect ending date" 

    SetFocusOnError="true"

    Display="None">&nbsp</asp:CustomValidator>

Open in new window

0
Comment
Question by:karakav
  • 9
  • 5
  • 4
  • +1
22 Comments
 
LVL 20

Expert Comment

by:informaniac
ID: 22631633
This should work
function compareStartEnd()

{ 

var stringFromDate = document.getElementById('<%=txtStart.ClientID%>').value;

var stringToDate = document.getElementById('<%=txtEnd.ClientID%>').value;
 

var FromDate = Date.parse(stringFromDate);

                var ToDate = Date.parse(stringToDate);

                if (FromDate > ToDate)

                    alert('The end date must be greather than the start date');

}

Open in new window

0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22631636
modified the code for compareStartEnd
function compareStartEnd()

{

var one = document.getElementById('<%=txtStart.ClientID%>').value;

    var two = document.getElementById('<%=txtEnd.ClientID%>').value;

   

   if(Date.parse(one) >Date.parse(two))

    {

        alert('The end date must be greather than the start date');

//        document.getElementById('<%=txtEnd.ClientID%>').focus();

    } 

}

Open in new window

0
 
LVL 4

Author Comment

by:karakav
ID: 22632547
I doesn't work. I put     alert(one + '' + two ); inside compareStartEnd()
 and I get NaN.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 22632632
Where did u place the alert?
After this

////if(Date.parse(one) >Date.parse(two))

or before this
0
 
LVL 4

Author Comment

by:karakav
ID: 22632833
After. And now that you asked, I put it before and I got an empty string.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 22632861
Are you leaving the textbox blank?

This won't work if the textbox is empty...
Also, please alert this..and tell the output

alert('<%=txtStart.ClientID%>');
0
 
LVL 4

Author Comment

by:karakav
ID: 22633085
I am not let any field empty. And the alert gives me stange result.  Actually on my aspx page, I have many instances of the user control. With the alert you asked me to fire, I get the Id of the last instance of the control, different from the one I want to check the values. And when I put the values in that control, the comparison work without problems.  I don't what is wrong with the other controls.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 22633200
If u r having a fixed number of ur user controls on the page... then just write the id that is generated on runtime by viewing the source of the page...
0
 
LVL 4

Author Comment

by:karakav
ID: 22633394
The problem is that I want that comparison to be carried out inside the user control.
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22640090
karakav:
i create a web user control and tested, only thing is i comment the validateDate() part as i think it is in your textboxdata assembly..
here is the code for user control,my test page and output attached.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

 

<head >

    <title>Untitled Page</title>

    <script language="javascript" type="text/javascript">

 

function validateDates(source, arguements)

{
 

    var thevalue = arguements.Value;

    

    arguements.IsValid=false;    

    

//    if(!validateDate(thevalue))

//    {

//        alert(source.errormessage);

//        return;

//    }

    arguements.IsValid=true;  

            

}

function compareStartEnd()

{ 

var one = document.getElementById('<%=txtStart.ClientID%>').value;

    var two = document.getElementById('<%=txtEnd.ClientID%>').value;

    alert(one + '' + two ); 

   if(Date.parse(one) >Date.parse(two))

    {

        alert('The end date must be greather than the start date');

//        document.getElementById('<%=txtEnd.ClientID%>').focus();

    } 

alert(one + '' + two );  

}   

    </script>

</head>

<table width="100%">

    <tr>

        <td align="right" width="75%">

            <asp:Label ID="lblCaption" runat="server" Text="Title: " Font-Names="Verdana" Font-Size="10px" ForeColor="#000000"></asp:Label>

        </td>

        <td align="left" width="10%">

            <asp:TextBox 

                ID="txtStart" 

                runat="server" 

                MaxLength="10" 

                Width="80px"             

                style="padding: 2px;border:solid 1px #92C86A;background-color: #ffffff;font-family:Verdana;font-size: 11px;color:#000000;"

                onfocus="this.select();"></asp:TextBox>

         </td>

         <td align="center" width="5%">

            <span style="font-family:Verdana;font-size: 10px;font-weight:bold;color:#000000;">-</span>	        

         </td>

         <td align="left" width="10%">

            <asp:TextBox 

                ID="txtEnd" 

                runat="server" 

                MaxLength="10" 

                Width="80px" 

                style="padding: 2px;border:solid 1px #92C86A;background-color: #ffffff;font-family:Verdana;font-size: 11px;color:#000000;" 

                onfocus="this.select();" 

                onchange="compareStartEnd();" ></asp:TextBox>

        </td>            

    </tr>            

</table>

<asp:CustomValidator 

    ID="cuvStart" 

    runat="server" 

    ControlToValidate="txtStart" 

    ClientValidationFunction="validateDates" 

    ErrorMessage="Incorrect starting date." 

    SetFocusOnError="true"

    Display="None">&nbsp</asp:CustomValidator>

<asp:CustomValidator 

    ID="cuvEnd" 

    runat="server" 

    ControlToValidate="txtEnd" 

    ClientValidationFunction="validateDates" 

    ErrorMessage="Incorrect ending date" 

    SetFocusOnError="true"

    Display="None">&nbsp</asp:CustomValidator>
 
 

------

test page
 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 

<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

<asp:LinkButton runat="server" id="lbtTemp" OnClick="DeleteJob">LinkButton</asp:LinkButton>

 <asp:Label runat="server" ID="lblStatus" ></asp:Label>

 <asp:TextBox runat="server" ID="txtStart" ></asp:TextBox>

 <asp:TextBox runat="server" ID="txtEnd" ></asp:TextBox>

 <img id="img" alt="test" src="#" onmouseover="mouseoverfunction" onclick="clickfunction();" />

        <uc1:WebUserControl ID="WebUserControl1" runat="server" />
 

 

   
 

    </div>

    </form>

</body>

</html>

<script type ="text/javascript" >

function mouseoverfunction()

{}

function clickfunction()

{

   var one = document.getElementById('<%=txtStart.ClientID%>').value;

    var two = document.getElementById('<%=txtEnd.ClientID%>').value;

   alert(one + '' + two ); 

   if(Date.parse(one) >Date.parse(two))

    {

        alert('The end date must be greather than the start date');

//        document.getElementById('<%=txtEnd.ClientID%>').focus();

    } 

alert(one + '' + two ); 

}

    

</script>

Open in new window

custom-control.JPG
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 4

Author Comment

by:karakav
ID: 22648233
Try to put other instances of the same user control. You will fail in validation.
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22649013
Yes. It is failing.. let me have another look.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22723981
Hi karakav,
Is there any reason that you don't use the built-in validators, such as RegularExpressionValidator and CompareValidator, to accomplish your task?
0
 
LVL 4

Author Comment

by:karakav
ID: 22724192
I didn't use those in this particular case because on of the requirement was to display a popup message upon validation failure. The only validation control that was giving me that possibility was the custom validator. I couldn't use the validation summary neither.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22724814
So all you need to compare the two text boxes to make sure the end date is greater than the start date? No worry about the empay data or format?
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22726165
Ok, I assume the answer to those questions is "yes".
I would like you to try this (without using CustomValidator):
1. Add a CompareValidator to your user control as attached code snippet.
2. Change your JavaScript function as shown in the code snippet.
It should work for multiple instances of the user control. Let me know if it works for you.
 

// CompareValidator

<asp:CompareValidator ID="cvStartEndCompare" runat="server" ControlToCompare="txtStart"

    ControlToValidate="txtEnd"

    Operator="GreaterThan" Type="Date" Enabled="True"></asp:CompareValidator>
 

//Modified JavaScript

function compareStartEnd()

{

	var val = document.getElementById('<% =cvStartEndCompare.ClientID %>');

	ValidatorEnable(val, true);

	if (Page_IsValid != true)

	{

		alert('The end date must be greater than the start date.');

	}

}

Open in new window

0
 
LVL 4

Author Comment

by:karakav
ID: 22728459
I apologize because I was absent when you asked your question. Actually the answer was no because I need to validate both fields before. And I guess in this case your solution is not viable.
0
 
LVL 22

Expert Comment

by:prairiedog
ID: 22731198
Do you also want to use alert to notify user if any of the fields is empty, or the format is invalid?
Honestly, I don't like "alert" for this kind of notification, because it doesn't tell you which field is required if you have multiple instances of the user control on your page. I prefer to user RequiredFieldValidator and RegularExpressionValidator because they display the error messages right next to the field.
Anyway, it is your call. If you want to use alert, it is fine to me and I will post more code to accomodate it after I get your response.
P.S. please at least give my code a try (with both fields filled with right dates, but with end date < start date) to see if it works for you.
0
 
LVL 4

Author Comment

by:karakav
ID: 22738185
I do understand your concern and I like this way of doing also. However in this case, I am working on a project that was started by a colleague and I want to do things the way she does it. And a fact is that she likes a lot alerts.

P.S.: I do understand you mean in your last comment. If you want to see the how to control works, I don't think your need me to post a code as you already have the code snippet in the first comment I sent.
0
 
LVL 22

Accepted Solution

by:
prairiedog earned 500 total points
ID: 22740451
Understood.
If you have already taken care of the validation for empty input and valid date format, then you can use the code I provided. I tested it on my machine and it works. Based on your original post, it seems that the only thing you need is to make compareStartEnd work.
0
 
LVL 4

Author Closing Comment

by:karakav
ID: 31502669
Thanks.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now