1

I don't know why I'm having so much trouble searching this, it seems really easy, but I can't find any information.

Basically I want a control on my ASP.net form to be updated depending on what number is in a field.

So if I had 0x0= it would show 0, and if i changed the number to 5x5= it would automatically display 25 (as soon as I finished typing it)

Edit: I don't really have a good code sample, here is an example of what I want.

<asp:textbox></asp:textbox>X<asp:textbox></asp:textbox> = <asp:label text="value of the last two being changed dynamically" />
proseidon
  • 2,235
  • 6
  • 33
  • 57

4 Answers4

2

The following will calculate the input when an = symbol is entered, and replace the value with the result of the calcuation.

Therefore:

  • 5*5= will be replaced with 25
  • 5x5= will be replaced with 25
  • 5+5= will be replaced with 10

$("input").keyup(function(){
       var $this = $(this);
        if ($this.val().indexOf("=")>=0){
           $this.val(eval($this.val().replace("=", "").replace("x","*")));
        }            
    });

http://jsfiddle.net/QP8ay/1/

This method uses eval() to convert the string into a calculation. However this isn't very safe:

Why is using the JavaScript eval function a bad idea?

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
2

Using try..catch with eval()

I've created an unsafe example on JSFiddle that does what you require but instead of waiting for result when caret is still on the input box, I attached to blur event so value gets evaluated when you switch focus outside of the control.

What it does is this:

$("input").blur(function(evt) {
    try {
        var val = eval(this.value);
        this.value = val;
    }
    catch (e) {}
});

It tries to evaluate content of the input box and if it was able to do so, replace content with the result. This means that you can throw anything at it as long as eval can chew on it.

I said unsafe, because code's not checking content for anything that could cause black holes to swallow universes... ;)

Examples

  • 1 + 2 * 3 will change 7
  • universe will leave it as universe
  • 010+1 will change to 9 (so it groks octals as well)
  • 0xf *2 +3 will return 33 (look ma' hex as well)
  • etc.

Implement your way to make it safer

This is of course just a start. If you'd like x to be become multiplicator, you will have to do some replacements in input string, that my example doesn't do. But it's pretty straight forwards to do so.

The same is true if you'd only like to do particular calculations, so you don't allow creating objects or dates or anything...

An example that is likely undesirable in your case is if you'd type in

alert(new Date())

which would of course execute this code and display an alert box. Whether you'd like to allow this or not is on you. If you'd be posting original data to server yu'd of course want to sanitize inputs severely.

Community
  • 1
  • 1
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
1

You should be able to bind to the change event and get the value of the source input and then use that to populate your other control, something like

 $('#inputSource').on('change', function(e) {        
       var value = $(this).val();
       if (value.match('=')) {
           value = value.replace('=','');
           numbers = value.split('x');
         if (numbers.length > 1) {
           $('#controlToBeUpdated').val(parseInt(numbers[0]) * parseInt(numbers[1]));
         }
       }
    };

Of course you will need to add some validation to make sure that the values are numbers etc.

Jack
  • 10,943
  • 13
  • 50
  • 65
0

I would use the following:

$(function() {
    "use strict";
    var valid = /^[\d]+[x\/\*+\-][\d]+=$/i;

    $("#calc").on("keyup", function( e ) {
        var $this = $(this);
        if ( e.keyCode === 48 ) {
            if ( valid.test(this.value) ) {
                $this.val(eval($this.val().replace("=", "").replace("x","*")));
            }
        }
    });
});

As eval is evil and unsafe, better check first if this calculation actually is valid. Also checking if the actually = key is pressed.

See following fiddle: http://jsfiddle.net/sQVe/DSDQ2/

sQVe
  • 1,977
  • 12
  • 16