0

I am providing a form where the user shall enter an arithmetic calculation. Further down the result shall appear, once the user hits enter. It might just be a problem of syntax, but I couldn't find the mistake. Here is what I did so far:

<!DOCTYPE html>
<html>
<body>
<p>What do you want to calculate?</p>
<form method="post"><span>Type here:</span><input type="text" id="calc"></input>
</form>
<script>
num_field = document.getElementById("calc");
num_field.onsubmit=function ()
{
    document.getElementById("display_result").innerHTML = num_field;
}
</script>
<p id="display_result"></p>
</body>
</html>

So, the user shall enter for instance "1+2". The result shall appear below. Any idea where is my mistake?

Best regards

user9
  • 145
  • 1
  • 12
  • 2
    [input-element](https://developer.mozilla.org/en/docs/Web/HTML/Element/input) is self-closing and should not have end tag. – Esko May 24 '17 at 09:30

5 Answers5

1

You were nearly there, your code just needed a bit of tweaking - see below (comments in code as what I have done and why)

The following seems to be an alternate and safer way to do this without using eval (function taken from the second answer in this post):

<!DOCTYPE html>
<html>

<body>
  <p>What do you want to calculate?</p>
  <form method="post" id="form">
    <span>Type here:</span>
    <input type="text" id="calc">              <!-- inputs are self closing no need for closing tag -->
    <input type="submit" value="submit">       <!-- added a submit button -->
  </form>
  <script>
    form = document.getElementById("form");
    num_field = document.getElementById("calc");
    form.onsubmit = function() {                                              // attach this event to the form
      document.getElementById("display_result").innerHTML = evalAlternate(num_field.value);  // add .value here to get the value of the textbox
      return false;                                                           // return false so form is not actually submitted and you stay on same page (otherwise your display result will not be updated as the page is reloaded
    }

 
    function evalAlternate(fn) {             // function safer alternate to eval taken from here: https://stackoverflow.com/questions/6479236/calculate-string-value-in-javascript-not-using-eval
      fn = fn.replace(/ /g, "");
      fn = fn.replace(/(\d+)\^(\d+)/g, "Math.pow($1, $2)");
      return new Function('return ' + fn)();
    }
  </script>
  <p id="display_result"></p>
</body>

</html>
Pete
  • 57,112
  • 28
  • 117
  • 166
  • Perfect. Thanks, Pete. – user9 May 24 '17 at 10:29
  • Actually, I just noticed that there is a slight problem. Potency should be recognised, right? If I enter 2^2 it gives me 0. – user9 May 24 '17 at 10:35
  • Not sure if there is a function that will recognise that in js - don't even think eval would - what answer would you expect and how do you come to that answer - I've never seen that in maths before – Pete May 24 '17 at 10:38
  • 1
    Well, in that case, I would maybe display message like "cannot solve it!". Otherwise it looks like it calculates wrong. I will work on it. Thanks. – user9 May 24 '17 at 10:47
  • I googled it and found it means to power - you could write in some functionality to see if there is a ^ and then use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/pow – Pete May 24 '17 at 10:53
1

Here is how you can achieve that.

eval is the best way for doing that but eval is risky to use so make sure to sanitize the value of input before using eval.

I am using this regex /(^[-+/*0-9]+)/g to extract only numbers and few operators (-+/*) and doing eval on that value.

remove the <form> that is not required use keypress event listener and check for enter key. keycode of enter key is 13

num_field = document.getElementById("calc");
num_field.onkeypress = function(e) {
  if(e.which==13)
  {
     var value = num_field.value.match(/(^[-+/*0-9]+)/g);
     if(!value) return;
     else value = value[0];
     var res = eval(value);
     document.getElementById("display_result").innerText = res;
  }
}
<p>What do you want to calculate?</p>
  <span>Type here:</span>
  <input type="text" id="calc" />
<p id="display_result"></p>
Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33
0

This should work:

calc = document.getElementById("calc");
formula = document.getElementById("formula");
calc.addEventListener('click', function() {
  document.getElementById("display_result").innerHTML = eval(formula.value);
});
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="formula" />
<button id="calc" type="submit">calc</button>
<p id="display_result"></p>

eval() JavaScript Method

Sebastian
  • 1,109
  • 4
  • 17
  • 33
  • 1
    eval() is evil https://duckduckgo.com/?q=eval+is+evil&atb=v63-1__&ia=web – jmtalarn May 24 '17 at 09:36
  • Thanks again for all the alternatives. I learnt a lot. I think which one I should prefer depends on the concrete task. – user9 May 24 '17 at 10:31
0

Try this:

var calculation_input = document.getElementById('calculation_input');
calculation_input.onkeydown = function(event) {
  if (event.keyCode == 13) { // Enter key.
    // Sanitize before using eval()
    var calculation = calculation_input.value.replace(/[^-()\d/*+.]/g, '');
    document.getElementById("display_result").innerHTML = eval(calculation);
  }
}
<p>What do you want to calculate?</p>
<span>Type here:</span>
<input type="text" id="calculation_input" />
<p id="display_result"></p>

You don't need to submit the calculation in a form, you can just use native javascript to calculate the result. And don't forget to always sanitize before using eval :)

Ethan
  • 4,295
  • 4
  • 25
  • 44
0

see the below fiddle

https://jsfiddle.net/ponmudi/13y9edve/

num_field = document.getElementById("calc");
num_field.onkeydown = (event) => {
    if (event.keyCode === 13) {
        document.getElementById("display_result").innerHTML = eval(num_field.value);
        return false;
    }
}
Ponmudi VN
  • 1,493
  • 1
  • 18
  • 22