Solved

How to change web page text box when leaving another text box

Posted on 2009-04-08
24
226 Views
Last Modified: 2013-11-07
I have a textbox on a web page that needs to be filled with the sum of 2 other text boxes.  So when I leave textbox a or textbox b , then textbox c calculates and has the new value.  The problem is I need to set postback = true on textbox a or b, but I also have requiredfield validaters that end up showing up, because left textbox a or textbox b.  So I'm hoping for a idea to reculate a textbox without having to set postback = true

thanks in advance.
Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then
            txtPayAmt.Text = FormatCurrency(Session("vBalance"))
            txtCFee.Text = FormatCurrency(18, 2)
            txtTotalCharge.Text = FormatCurrency(CDbl(txtPayAmt.Text) + CDbl(txtCFee.Text), 2)
        Else
 
        End If
    End Sub
 
    Protected Sub txtPayAmt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPayAmt.TextChanged
        txtTotalCharge.Text = FormatCurrency(txtPayAmt.Text + txtCFee.Text, 2)
    End Sub

Open in new window

0
Comment
Question by:mgmhicks
[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
  • 12
  • 9
  • 3
24 Comments
 
LVL 8

Expert Comment

by:ppittle
ID: 24100114
mgmhicks,
Try the attached code which does the multiplication via javascript.  The onblur client side event kicks off the javascript multiply() function.  Onblur fires anytime focus leaves a control.  Additionally, multiply checks to make sure that there is a value in both text boxes and that the value is a valid number, otherwise it clears the value of the product text box.

PJ
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" >
    function multiply()
    {
        var int1TextBox = document.getElementById('Int1');
        var int2TextBox = document.getElementById('Int2');
        var productTextBox = document.getElementById('Product');
        
        if ((int1TextBox.value == '') || (int2TextBox.value == ''))
        {
            productTextBox.value = '';
        }
        else if ((isNaN(int1TextBox.value)) || (isNaN(int2TextBox.value)))
        {
            productTextBox.value = '';
        }        
        else
        {        
            productTextBox.value = parseInt(int1TextBox.value) * parseInt(int2TextBox.value);
        }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server" >
    <div>      
        <asp:TextBox ID="Int1" runat="server" onblur="multiply()"  /> x <asp:TextBox ID="Int2" runat="server" onblur="multiply()" />
        =
        <asp:TextBox ID="Product" runat="server" />        
    </div>
    
    </form>
</body>
</html>

Open in new window

0
 
LVL 15

Expert Comment

by:spprivate
ID: 24100191

In code behind
Imports System
 
Partial Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtA.Attributes.Add("onblur", "javascript:add()")
        txtB.Attributes.Add("onblur", "javascript:add()")
 
 
    End Sub
End Class
 
HTML
<head runat="server">
    <title>Untitled Page</title>
    <script type ="text/javascript">
    function add()
    {
    var x = document.getElementById('txtA')
    var y = document.getElementById('txtB')
    var z = document.getElementById('txtans')
    z.value=parseInt(x.value) + parseInt(y.value)
 
    }
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtA" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtB" runat="server"></asp:TextBox>&nbsp;
        <asp:TextBox ID="txtans" runat="server"></asp:TextBox></div>
    </form>
</body>

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24100442
sppirate, looks like its doing something but it comes back with value in textbox of NaN.  Any ideas?
0
Guide to Performance: Optimization & Monitoring

Nowadays, monitoring is a mixture of tools, systems, and codes—making it a very complex process. And with this complexity, comes variables for failure. Get DZone’s new Guide to Performance to learn how to proactively find these variables and solve them before a disruption occurs.

 
LVL 8

Expert Comment

by:ppittle
ID: 24100514
spprivate's javascript doesn't ensure there's actually values in txtA and txtB before performing the calculations.  Modify it as so.  Now it will check to ensure there's actually a value in both text boxes and that value is a number.  Otherwise nothing will be displayed in txtans.
function add()
    {
    var x = document.getElementById('txtA')
    var y = document.getElementById('txtB')
    var z = document.getElementById('txtans')
 
 if ((x.value == '') || (y.value == ''))
        {
            z.value = '';
        }
        else if ((isNaN(x.value)) || (isNaN(y.value)))
        {
            z.value = '';
        }        
        else
        {       
    z.value=parseInt(x.value) + parseInt(y.value)
 }
    }

Open in new window

0
 
LVL 15

Expert Comment

by:spprivate
ID: 24101095
yeah,it was a quick fix.thanks ppittle
0
 
LVL 8

Expert Comment

by:ppittle
ID: 24101122
spprivate -> No problem.  Gotta love the fringe cases :)
0
 

Author Comment

by:mgmhicks
ID: 24101970
ok, now nothing comes back, problem is that these are text values in the text box.  Can I convert in the java script?
0
 
LVL 8

Expert Comment

by:ppittle
ID: 24102019
Are you saying your users will be spelling out the numbers as opposed to entering numerical values into the text boxes?  Ie typing in "one" as opposed to "1"?
0
 

Author Comment

by:mgmhicks
ID: 24102053
No, I'm sorry they are binded to a dataset and they are string values.  I use this when I calculate wondering if I have to do something like this in the java script.

FormatCurrency(CDbl(txtPayAmt.Text) + CDbl(txtCFee.Text), 2)

thanks

     
0
 
LVL 15

Expert Comment

by:spprivate
ID: 24102127
The parseint will convert string to integer.
Anyway for you to have the currency format here is a snippet.Pass the x and y value to this function and you get currency.So for eg

var x = CurrencyFormatted(document.getElementById('txtA').value);

function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24102283
I'm sorry still nothing.  Not changing values at all.  No errors.  Here is what is in the html

<script type ="text/javascript">
     {
    var x = CurrencyFormatted(document.getElementById('txtPayAmt').value);
    var y = document.getElementById('txtCFee')
    var z = document.getElementById('txtTotalCharge')
    
 
 
 if ((x.value == '') || (y.value == ''))
        {
            z.value = '';
        }
        else if ((isNaN(x.value)) || (isNaN(y.value)))
        {
            z.value = '';
        }        
        else
        {       
    z.value=parseInt(x.value) + parseInt(y.value)
 }
    }
    function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
     </script>

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24102361
spprivate seems like the java script isnt being hit when I click out of the txtPayamt text box after changing the amount.  I am hitting the function
 Protected Sub txtPayAmt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPayAmt.TextChanged
        txtPayAmt.Attributes.Add("onblur", "javascript:add()")
        txtCFee.Attributes.Add("onblur", "javascript:add()")
    End Sub

thanks again
0
 
LVL 8

Expert Comment

by:ppittle
ID: 24102384
Try inserting the text "function add()" on line two before the curly bracket ("{")
0
 

Author Comment

by:mgmhicks
ID: 24102511
man still nothing.  Here is what it looks like now.


<script type ="text/javascript">
    Function(Add)
     {
    var x = CurrencyFormatted(document.getElementById('txtPayAmt').value);
    var y = document.getElementById('txtCFee')
    var z = document.getElementById('txtTotalCharge')
    
 
 
 if ((x.value == '') || (y.value == ''))
        {
            z.value = '';
        }
        else if ((isNaN(x.value)) || (isNaN(y.value)))
        {
            z.value = '';
        }        
        else
        {       
    z.value=parseInt(x.value) + parseInt(y.value)
 
    }
    
    function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
     </script>

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24103876
On the code behind page where we have the
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtA.Attributes.Add("onblur", "javascript:add()")
        txtB.Attributes.Add("onblur", "javascript:add()")
 
 
    End Sub
if I ctrl-click to follow link on those I get a error say expecting object.  Any more ideas
0
 
LVL 8

Expert Comment

by:ppittle
ID: 24118885
Line 2 in your last code snippet should read:
Function Add()

You currently have:
Function (Add)

Additionally, don't work about VS giving you an error when ctrl-click to follow 'the link' it shows in the codebehind.  That's just the VS being stupid.  It shouldn't show a link at all.
0
 

Author Comment

by:mgmhicks
ID: 24122502
ok here is the error I'm getting now.  It doesnt seem to be hitting the javascript on the web page at all.  This error is coming from the vb code behind.  Here is the error and the code is attached.

{"c:\inetpub\wwwroot\Memberships\MemberPages\Resident_CHK.aspx(349): error BC30456: 'Add' is not a member of 'ASP.memberpages_resident_chk_aspx'."}

Could 2 javascript statements be my problem.  I havent done much with the javascript obviously.  Please dont quit on me.  I really need this.
thanks

VB CODE:
Protected Sub txtPayAmt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPayAmt.TextChanged
        'txtPayAmt.Attributes.Add("onblur", "jscript:add()")
        txtCFee.Attributes.Add("onTextChange", "javascript:add();")
    End Sub
 
WEB PAGE CODE
<head>
<script language = "javascript" type ="text/javascript"  src="http://localhost/memberships/Flash/flashobject.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>The Apartment Gallery</title>
<script language = "javascript" type ="text/javascript">
 
    function add()
    {
    var x = CurrencyFormatted(document.getElementById('txtPayAmt').value);
    var y = CurrencyFormatted(document.getElementById('txtCFee').value)
    var z = CurrencyFormatted(document.getElementById('txtTotalCharge').value)
    z.value=parseInt(x.value) + parseInt(y.value) 
    }
 
    function CurrencyFormatted(amount)
    {
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
    }
 
     </script>

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24122899
ppittle I now release that after leaving the text box it get a web page error.

Line 1
char 1
Error: Object expected
code 0
url http://localhost/memberships/memberpages/resident_chk.aspx

thats the page the text box and java script are on.
0
 

Author Comment

by:mgmhicks
ID: 24132254
ok, we have to much time on this to quit.  I have reduced the code significantly to help find the error.  Now the only problem I have is when I change the txtpaymentAmt field it comes back NaN in the txtTotalCharge field.  Please look at script and see what we can do .  currencyformat doesnt seem to help.  Thanks again

<script  type ="text/javascript">
 
function Add()
   {
   var x = parseFloat(document.getElementById("txtPaymentAmt").value);
   var y = parseFloat(document.getElementById("txtCFee").value);
   var z = parseFloat(x.value + y.value);
   
//  var x = CurrencyFormatted(document.getElementById("txtPaymentAmt").value);
//   var y = CurrencyFormatted(document.getElementById("txtCFee").value);
//    var z = CurrencyFormatted(document.getElementById("txtTotalCharge").value);
//    z.value=parseInt(x.value) + parseInt(y.value); 
    document.getElementById("txttotalcharge").value = z;
   }
 
// function CurrencyFormatted(amount)
//    {
//	var i = parseFloat(amount);
//	if(isNaN(i)) { i = 0.00; }
//	var minus = '';
//	if(i < 0) { minus = '-'; }
//	i = Math.abs(i);
//	i = parseInt((i + .005) * 100);
//	i = i / 100;
//	s = new String(i);
//	if(s.indexOf('.') < 0) { s += '.00'; }
//	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
//	s = minus + s;
//return s;
//   }
</script>
 
<asp:TextBox ID="txtPaymentAmt" onblur="Add()" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
 
 
 
VB Code
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        txtPaymentAmt.Text = CDbl(Session(9))
        txtCFee.Text = CDbl(1)
        txtTotalCharge.Text = CDbl(txtPaymentAmt.Text) + CDbl(txtCFee.Text)
 
End Sub

Open in new window

0
 
LVL 8

Expert Comment

by:ppittle
ID: 24132455
Take a look at this revision.
<head runat="server">
    <title>Untitled Page</title>
 
    <script type="text/javascript">
 
function Add()
{
    var txtPaymentAmount = document.getElementById('txtPaymentAmt')
    var txtCFee = document.getElementById('txtCFee')
    var txtTotalCharge = document.getElementById('txtTotalCharge')
 
    if ((txtPaymentAmount.value == '') || (txtCFee.value == ''))
    {
        txtTotalCharge.value = '';
    }
    else if ((isNaN(txtPaymentAmount.value)) || (isNaN(txtCFee.value)))
    {
        txtTotalCharge.value = '';
    }        
    else
    {       
        txtTotalCharge.value=parseFloat(txtPaymentAmount.value) + parseFloat(txtCFee.value)
    }
}
 
 
    </script>
 
</head>
<body>
    <form id="form1" runat="server">       
        Payment Amount: <asp:TextBox ID="txtPaymentAmt" onblur="Add()" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
        CFee: <asp:TextBox ID="txtCFee" runat="server" onblur="Add()" />
        <br />
        Total Charge: <asp:TextBox ID="txtTotalCharge" runat="server" />
    </form>
</body>
</html>

Open in new window

0
 

Author Comment

by:mgmhicks
ID: 24132756
Ok txtcfee field once I set it in code it will not be editable.  The only thing the user can edit is the txtpaymentamt.  I changed your code to stop from giving me a error, however the dollar amount is not being changed.  Here is the code again.
WEB PAGE
 
function AddMe()
{
    var txtPaymentAmount = parseFloat(document.getElementById('txtPaymentAmt'))
    var txtCFee = parseFloat(document.getElementById('txtCFee'))
    var txtTotalCharge = parseFloat(document.getElementById('txtTotalCharge'))
 
    if ((txtPaymentAmount.value == '') || (txtCFee.value == ''))
    {
        txtTotalCharge.value = '';
    }
    else if ((isNaN(txtPaymentAmount.value)) || (isNaN(txtCFee.value)))
    {
        txtTotalCharge.value = '';
    }        
    else
    {       
        txtTotalCharge.value=parseFloat(txtPaymentAmount.value) + parseFloat(txtCFee.value)
    }
}
 
<asp:TextBox ID="txtPaymentAmt" onblur="AddMe()" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
 
VB Code Behind:
 txtPaymentAmt.Text = (CDbl(Session(9)))
        txtCFee.Text = (CDbl(1))
        txtTotalCharge.Text = (CDbl(txtPaymentAmt.Text)) + (CDbl(txtCFee.Text))

Open in new window

0
 
LVL 8

Accepted Solution

by:
ppittle earned 500 total points
ID: 24132807
Can you give me an example of what you're setting txtPaymentAmt.Text and txtCFee.Text to in the code-behind?  Ie "$5.42" and "$0.23" or "5.42" and "0.23"?
0
 

Author Closing Comment

by:mgmhicks
ID: 31569679
Ok, between what you sent me and what I was able to figure out, I did get it to work.  Here is the final code.  Thank you for the help.  You deserve the points.

VB Code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim x As Double
        Dim y As Double
        txtPaymentAmt.Text = Format(CDbl(Session(9)), "0.00")
        txtCFee.Text = Format(CDbl(1), "0.00")
        x = Format(CDbl(txtPaymentAmt.Text), "0.00")
        y = Format(CDbl(txtCFee.Text), "0.00")
        'txtTotalCharge.Text = x + y
        txtTotalCharge.Text = Val((Format(CDbl(txtPaymentAmt.Text), "0.00")) + Val(Format(CDbl(txtCFee.Text), "0.00")))
        '    txtPaymentAmt.Attributes.Add("onblur", "javascript:add()")
        '    'txtCFee.Attributes.Add("onblur", "javascript:add()")

        'End Sub


        'Protected Sub txtPaymentAmt_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPaymentAmt.TextChanged
        '    txtPaymentAmt.Attributes.Add("onblur", "javascript:add()")
        ' end sub

    End Sub

WEB PAGE

function Add()
   {
   var x = parseFloat(document.getElementById("txtPaymentAmt").value);
   var y = parseFloat(document.getElementById("txtCFee").value);
   var z = x.value + y.value;
   document.getElementById("txtTotalCharge").value = formatNumber(x+y);
 
   }
function formatNumber(num){
return num.toFixed(2).toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'$1,').split('').reverse().join('').replace(/^[\,]/,'');
}
0
 
LVL 8

Expert Comment

by:ppittle
ID: 24132920
Alright!  Glad we finally cracked that one!  Happy coding.
0

Featured Post

MS Dynamics Made Instantly Simpler

Make Your Microsoft Dynamics Investment Count  & Drastically Decrease Training Time by Providing Intuitive Step-By-Step WalkThru Tutorials.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
API v SOA 8 44
Visual Studio hangs on running project 6 64
Include MS Database in Winforms Project using Intellilock 5 21
Broken .resx file generating errors 18 27
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

696 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