Link to home
Start Free TrialLog in
Avatar of mgmhicks
mgmhicks

asked on

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

Avatar of ppittle
ppittle
Flag of United States of America image

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


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

Avatar of mgmhicks
mgmhicks

ASKER

sppirate, looks like its doing something but it comes back with value in textbox of NaN.  Any ideas?
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

yeah,it was a quick fix.thanks ppittle
spprivate -> No problem.  Gotta love the fringe cases :)
ok, now nothing comes back, problem is that these are text values in the text box.  Can I convert in the java script?
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"?
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

     
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

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

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
Try inserting the text "function add()" on line two before the curly bracket ("{")
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

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
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.
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

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.
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

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

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

ASKER CERTIFIED SOLUTION
Avatar of ppittle
ppittle
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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(/^[\,]/,'');
}
Alright!  Glad we finally cracked that one!  Happy coding.