[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2009-04-21
6
Medium Priority
?
481 Views
Last Modified: 2012-05-06
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
Comment
Question by:techques
  • 4
  • 2
6 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 24197039
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
 

Author Comment

by:techques
ID: 24201744
I would like to have a drop down with the following option value:

*
/
+
-

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 24204454
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:techques
ID: 24302705
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
 
LVL 41

Accepted Solution

by:
HonorGod earned 150 total points
ID: 24305400
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
 
LVL 41

Expert Comment

by:HonorGod
ID: 24312959
I'm sorry that you only thought the answer warranted a B

Good luck & have a great day
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
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…
Suggested Courses
Course of the Month18 days, 6 hours left to enroll

830 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