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

How js to set +-*/ in a textbox and make calculation?

Hi

I use javascript and asp.net.
In the aspx form, there are 3 textbox:

rate, amount, countervalue

The following js can auto-calculate the countervalue when I input amount and rate:
amount / rate = countervalue

However, it can only calculate '/'

If I need to calculate * or +  or -, I want to add a textbox 'math'

But, objRec.Fields("countervalue").value = (amountVal math rateVal).toFixed(4);   did not work.

How should I fix it?


function Calc(obj) {
          var objRec = xmlindata.recordset;
          if ( objRec ) {
            objRec.absolutePosition = obj.recordNumber;
            var amountVal = eval( objRec.Fields("amount").value )
            var rateVal   = eval( objRec.Fields("rate").value ).toFixed(4);
            objRec.Fields("countervalue").value = (amountVal / rateVal).toFixed(4);  
          }
        }
 
function Calc(obj) {
          var objRec = xmlindata.recordset;
          if ( objRec ) {
            objRec.absolutePosition = obj.recordNumber;
            var amountVal = eval( objRec.Fields("amount").value )
            var rateVal   = eval( objRec.Fields("rate").value ).toFixed(4);
            var math = eval( objRec.Fields("math").value )
            objRec.Fields("countervalue").value = (amountVal math rateVal).toFixed(4);  
          }
        }

Open in new window

0
techques
Asked:
techques
  • 4
  • 2
1 Solution
 
HonorGodSoftware EngineerCommented:
There are, of course, a number of ways to do this:

1. Have a drop down from which the operation to be performed may be selected (i.e., "+", "-", "*", or "/")

2. Evaluate the expression, (e.g., "1.23 + 4.56")

3. Have a radio button for each valid operation:

What do you prefer?

How does your HTML currently look?
0
 
techquesAuthor Commented:
I would like to have a drop down with the following option value:

*
/
+
-

0
 
HonorGodSoftware EngineerCommented:
Like this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Simple Calculator </title>
<script type='text/javascript'>
  function field( id ) {
    var ele = document.getElementById( id )
    if ( !ele ) {
      alert( 'Element not found. id="' + id + '"' )
    }
    return ele
  }
 
  function calc() {
    var amount = field( 'amount' )
    var rate   = field( 'rate' )
    var op     = field( 'op' )
    var result = field( 'result' )
    if ( amount && rate && op && result ) {
      var aVal = amount.value
      if ( aVal != '' ) {
        if ( /^\d+\.?\d*$/.test( aVal ) ) {
          var rVal = rate.value
          if ( rVal != '' ) {
            if ( /^\d+\.?\d*$/.test( rVal ) ) {
              var opVal = op.options[ op.selectedIndex ].value
              var express = aVal + ' ' + opVal + ' ' + rVal
              alert( 'Expression: "' + express + '"' )
              result.value = eval( express ).toFixed( 4 )
            } else {
              alert( 'calc(): Invalid rate "' + rVal + '"' )
            }
          }
        } else {
          alert( 'calc(): Invalid amount "' + aVal + '"' )
        }
      }
    }
  }
</script>
</head>
<body>
<input type='text' id='amount' onchange='calc()'>
<select id='op' onchange='calc()'>
  <option>+</option>
  <option>-</option>
  <option>*</option>
  <option>/</option>
</select>
<input type='text' id='rate'   onchange='calc()'>
<input type='text' id='result' readonly>
</body>
</html>

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

 
techquesAuthor Commented:
Hi

I tried your code with aspx textbox, since I use ascx user control, the id cannot be get properly. And, I changed to use radiobutton for * and /

Here is the code:

aspx: 
 
function field(id) {
            var ele = document.getElementById( id )
            if (!ele) {
              alert( 'Element not found. id="' + id + '"' )
            }
            return ele
        }
 
        function cald() {
            //not ok
            //var amount = field( 'ctl01_txtamount' )
            //var rate   = field( 'ctl01_txtrate' )
            //var op     = field( 'ctl01_op' )
            //var result = field( 'ctl01_txtcountervalue' )
            //not ok
            //var amount = document.getElementById('<%= txtamount.ClientID %>')
            //var rate   = document.getElementById('<%= txtrate.ClientID %>')
            //var op     = document.getElementById('<%= op.ClientID %>')
            //var result = document.getElementById('<%= txtcountervalue.ClientID %>')
            var op     = document.getElementById('ctl01_op_0')
            var rate   = document.getElementById('ctl01_txtrate')
            var amount = document.getElementById('ctl01_txtamount')            
            var result = document.getElementById('ctl01_txtcountervalue')
            if ( amount && rate && op && result ) {
              var aVal = amount.value
              if ( aVal != '' ) {
                if ( /^\d+\.?\d*$/.test( aVal ) ) {
                  var rVal = rate.value
                  if ( rVal != '' ) {
                    if ( /^\d+\.?\d*$/.test( rVal ) ) {
                      var opVal = op.options[ op.selectedIndex ].value
                      var express = aVal + ' ' + opVal + ' ' + rVal
                      alert( 'Expression: "' + express + '"' )
                      result.value = eval( express ).toFixed( 4 )
                    } else {
                      alert( 'cald(): Invalid rate "' + rVal + '"' )
                    }
                  }
                } else {
                  alert( 'cald(): Invalid amount "' + aVal + '"' )
                }
              }
            }
         }
 
<table border="0" width="98%" align="center" cellSpacing=0 cellPadding=0>
							<tr align=left>
							    <td align=left>Type</td><td align=left>Type</td><td align=left>Currency</td><td>Math</td><td>Rate</td><td>Amount</td><td>Counter Value</td><td>ClientReference</td><td>Remarks</td><td align=left>Account</td><td>HandlingIncome</td><td>HandlingExpense</td><td></td>
							</tr>
							<tr align=left>
							    <td align=left><asp:DropDownList Runat="server" ID="transactiontypeid" CssClass="form" AutoPostBack="True" Width=60 /></td>
							    <td align=left><asp:DropDownList Runat="server" ID="type" CssClass="form" AutoPostBack="True" Width=80 /></td>
							    <td align=left><asp:DropDownList Runat="server" ID="currency" CssClass="form" AutoPostBack="True" Width=60 /></td>
							    <td align=left><asp:RadioButtonList Runat="server" ID="op" RepeatDirection="Horizontal" TextAlign="Left" onchange='calt()'>
										<asp:ListItem Value="*" Selected="true">*</asp:ListItem>
										<asp:ListItem Value="/">/</asp:ListItem>
									</asp:RadioButtonList></td>
							    <td align=left><asp:textbox Runat="server" ID="txtrate" CssClass="form" Width=60 onchange='calt()' /></td>
							    <td align=left><asp:textbox Runat="server" ID="txtamount" CssClass="form" Width=100 onchange='calt()' /></td>
							    <td align=left><asp:textbox Runat="server" ID="txtcountervalue" CssClass="form" Width=100 onchange='calt()' /></td>
							    <td align=left><asp:textbox Runat="server" ID="txtclientreference" CssClass="form" Width=200 /></td>
							    <td align=left><asp:textbox Runat="server" ID="txtremarks" CssClass="form" Width=200 /></td>
							    <td align=left><asp:DropDownList Runat="server" ID="location" CssClass="form" AutoPostBack="True" Width=100 /></td>
							    <td align=left><asp:textbox Runat="server" ID="txthandlingincome" CssClass="form" Width=50 /></td>
							    <td align=left><asp:textbox Runat="server" ID="txthandlingexpense" CssClass="form" Width=50 /></td>
     							<td align="center"><asp:button id="btnSubmit3" runat="server" cssclass="button" text="submit" ></asp:button>
							</td>
						</tr>
</table>

Open in new window

0
 
HonorGodSoftware EngineerCommented:
If you change the "document.getElementById" in lines 22-25 to "field", then the field function will be called to do the call to document.getElementById(), and let you know if the specified documents aren't found.

So, change 22-25 to be:
            var op     = field('ctl01_op_0')
            var rate   = field('ctl01_txtrate')
            var amount = field('ctl01_txtamount')            
            var result = field('ctl01_txtcountervalue')

Open in new window

0
 
HonorGodSoftware EngineerCommented:
I'm sorry that you only thought the answer warranted a B

Good luck & have a great day
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

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now