Search code examples
javascriptvariablesinputformulaprompt

Javascript How do i get a mathematical expression in a Variable with window.prompt?


I have this Code, which isn't working properly. As you can see i try to get a formula in to an array. this is used to calculate the mathematical use later. but the programm don't put the formula in the right form right where the var stands:

<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">

var f, a, b, c, d, j, k, sum;

f = String(window.prompt("Formel"));
a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));





sum = 0;
for (j = a; j <= b; j++) {

    for (k = c ; k <= d ; k++) {
    sum += f;
    }
}

document.write(sum);

</script>
<noscript>
    <p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>

And i have this Code here, which calculate it right. But i would like to get the formula in to a var over the window.promp

<html>
<title> JavaScript Tutorial 1
</title>
<body>
<script language = "javascript">

var f, a, b, c, d, j, k, sum;

//f = String(window.prompt("Formel"));
a = Number(window.prompt("untere grenze 1tes E"));
b = Number(window.prompt("obere grenze 1tes E"));
c = Number(window.prompt("untere grenze 2tes E"));
d = Number(window.prompt("obere grenze 2tes E"));

sum = 0;
for (j = a; j <= b; j++) {

    for (k = c ; k <= d ; k++) {
    sum += j * j * k;
    }
}

document.write(sum);

</script>
<noscript>
    <p> You have JavaScript Turned Off <p>
</noscript>
</body>
</html>

Solution

  • @ yellowsir, thank you for your input, it works well with eval and i understand the security lack. As i just use this project for my self there will be no risk of someone putting in some malcode ;)

    Here is the Solution i got out of your input:

    <html>
    <title> JavaScript Tutorial 1
    </title>
    <body>
    <script language = "javascript">
    
    var f, a, b, c, d, j, k, sum;
    
    a = Number(window.prompt("untere grenze 1tes E"));
    b = Number(window.prompt("obere grenze 1tes E"));
    c = Number(window.prompt("untere grenze 2tes E"));
    d = Number(window.prompt("obere grenze 2tes E"));
    f = window.prompt("Formel");
    
    sum = 0;
    for (j = a; j <= b; j++) {
    
        for (k = c ; k <= d ; k++) {
        sum += eval(f);
        }
    }
    
    // document.write("<br>")
    document.write(sum);
    
    </script>
    <noscript>
    <p> You have JavaScript Turned Off <p>
    </noscript>
    </body>
    </html>
    

    Hopefully everything is clear do not hesitate to ask.