-3

How to add, subtract, multiply two numbers from a single input box?

e.g.: have input text box

<input type = "text" id = "id">

I need to add, subtract, multiply two numbers using the single text box. I have separate buttons for add, sub and multiply.

I have tried something like this:

var te = 0;
var input = false;
    function number(value){
            if(input === false){
                document.getElementById("id").value += value;
            }else{
                document.getElementById("id").value = value;
                input = false;
            }
    };
    
    function calc(opr){
    
        if(opr === '+'){
            te=te+parseInt(document.getElementById("id").value);
            document.getElementById("id").value = te;
            input = true;
            
        }
        
    };

Addition is working fine. I need to add multiplication, subtraction and equal to to this.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
localhost
  • 15
  • 4
  • 2
    you need two inputs for addition,subtraction..... – PSR Mar 09 '13 at 14:17
  • If you want to handle this in a single text box. Then you have to traverse and parse the string through javascript or at server side if you are using any server side language like php – Umair Saleem Mar 09 '13 at 14:19

2 Answers2

0

You could use the eval function. but first evaluate security and performance matters.

For more information about what should be accessible as variables from that text field you refers to Restricting eval() to a narrow scope

Community
  • 1
  • 1
Plap
  • 1,046
  • 1
  • 8
  • 14
0

Some steps:

1 - check whether the inputted value is a number
2 - split the number in single digits (or split the input value on a space)
3 - use the two number to do your transaction (add, substract, multiply)
4 - return it to the input-box

stUrb
  • 6,612
  • 8
  • 43
  • 71