0

This past school year I graduated from high school and I am now an intern at a small internet marketing company. My current task is to develop an online price estimator so that the salespeople can quickly provide consistent estimates for our services. This is my first Javascript project. The most advanced thing I accomplished in js previously was a just few small and basic dom manipulation tasks.

I found a site that has an estimator almost as robust as I need mine to be. So I am reading their code to figure out how it works so I can make my own version. I was told that it is bad practice to use eval() on user submitted data. So, I would like to know what to replace eval() with in this code.

    frm = document.form1;

    for (var i = 0; i < document.form1.elements.length; i++) {
        if (frm.elements[i].type == 'checkbox' || frm.elements[i].type                    == 'radio') {
            if (frm.elements[i].checked) {
            v = eval("frm.val" + frm.elements[i].value);
            mult = eval("frm.mult" + frm.elements[i].value);
            mult = mult.value;
            if (mult == '') {
                mult = 1
            } else {
                mult = parseInt(mult)
            }
            hrs = hrs + parseInt(v.value) * mult;
            var cur_val = frm.elements[i].title;
            var make_rfp = cur_val.replace("___", mult);
            document.getElementById('quote_des').value += make_rfp + "\n";
            }
        }
    }

Here is the site I pulled this code from: https://www.designquote.net/html/dq_estimate_wizard.cfm

  • Why is it bad to use eval on user submitted data? It would run any JS client side so they could only harm themselves. http://stackoverflow.com/questions/1651118/security-risks-of-using-eval-to-execute-user-input-in-javascript – Patrick Murphy Jun 24 '15 at 19:05

1 Answers1

1

Eval is bad practice because it executes pure javascript and if you allow your user to type any js in a textfield and then execute that, you have built an invitation for crosssitescripting ;-) It would allow your users to change the contents on your site and even send some manipulated data back to your server - if you have one.

What you are looking for is a library like mathjs that interprets a String as a mathematical formula. You can find some more info about that here Evaluating a string as a mathematical expression in JavaScript

The other option would be to write your own formular-parser, if the libraries don't do what you need, but that would be some more work.

Community
  • 1
  • 1
treeno
  • 2,510
  • 1
  • 20
  • 36