• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 237
  • Last Modified:

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

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
mgmhicks
Asked:
mgmhicks
  • 12
  • 9
  • 3
1 Solution
 
ppittleCommented:
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
 
spprivateCommented:

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
 
mgmhicksAuthor Commented:
sppirate, looks like its doing something but it comes back with value in textbox of NaN.  Any ideas?
0
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
ppittleCommented:
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
 
spprivateCommented:
yeah,it was a quick fix.thanks ppittle
0
 
ppittleCommented:
spprivate -> No problem.  Gotta love the fringe cases :)
0
 
mgmhicksAuthor Commented:
ok, now nothing comes back, problem is that these are text values in the text box.  Can I convert in the java script?
0
 
ppittleCommented:
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
 
mgmhicksAuthor Commented:
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
 
spprivateCommented:
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
 
mgmhicksAuthor Commented:
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
 
mgmhicksAuthor Commented:
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
 
ppittleCommented:
Try inserting the text "function add()" on line two before the curly bracket ("{")
0
 
mgmhicksAuthor Commented:
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
 
mgmhicksAuthor Commented:
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
 
ppittleCommented:
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
 
mgmhicksAuthor Commented:
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
 
mgmhicksAuthor Commented:
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
 
mgmhicksAuthor Commented:
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
 
ppittleCommented:
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
 
mgmhicksAuthor Commented:
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
 
ppittleCommented:
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
 
mgmhicksAuthor Commented:
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
 
ppittleCommented:
Alright!  Glad we finally cracked that one!  Happy coding.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

  • 12
  • 9
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now