Search code examples
jqueryevalparseint

Jquery eval variable and convert to currency


I have a jquery application where I need to evaluate variables in the form based on how many rows exist in the table.

The desired behavior is to find the selected option of the product, pull out the value (which then corresponds to the pre-defined price based on variable names), then do something with the price. I'm having issues with evaluating the variable name, converting to numbers, then using a currency plugin to convert to currency.

Here is the form:

    <table id="sizetable" class="table table-responsive table-condensed">
    <thead>
        <tr>
            <td width="30%">Shaft Type<input type="hidden" id="numfields" name="numfields" value="6"></td>
            <td width="25%">Team Message (Free)<br><small>Appears on every shaft - 24 character max</small></td>
            <td>&nbsp;</td>
            <td width="25%">Individual Message<br><small>+$5 each - 24 character max</small></td>
            <td>&nbsp;</td>
            <td width="10%">Shaft Price</td>
            <td width="10%"><button class="add_field_button btn btn-success">Add Shaft <span class="glyphicons glyphicons-circle-plus"></span></button></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><select name="toproduct1" id="toproduct1" class="toproduct">
                    <option value="28">Team Order Specialty Attack Shaft - $25.00</option>
                    <option value="29">Team Order Specialty Defense Shaft - $50.00</option>
                </select>
            </td>
            <td><input type="text" id="teammsg1" name="teammsg1" class="form-control" maxlength="24"></td>
                <td><span class="badge tmsgchr">0</span></td>
            <td><input type="text" id="indmsg1" name="indmsg1" class="form-control indmsg" maxlength="24"></td>
                <td><span class="badge indmsgchr1"></span></td>
            <td><span id="unitprice1"></span></td>
            <td><a class="remove_field btn btn-danger" disabled>Remove <span class="glyphicons glyphicons-circle-minus"></span></a></td>
        </tr>
        <tr>
            <td><select name="toproduct2" id="toproduct2" class="toproduct">
<option value="28">Team Order Specialty Attack Shaft - $25.00</option>
<option value="29">Team Order Specialty Defense Shaft - $50.00</option>
</select>
            </td>
            <td><span class="tmsg light-gray"></td>
                <td></td>
            <td><input type="text" id="indmsg2" name="indmsg2" class="form-control indmsg" maxlength="24"></td>
                <td><span class="badge indmsgchr2"></span></td>
            <td><span id="unitprice2"></span></td>
            <td><a class="remove_field btn btn-danger" disabled>Remove <span class="glyphicons glyphicons-circle-minus"></span></a></td>
        </tr>
...

The jquery I wrote is below:

$(document).ready(function() {  
    var max_fields      = 20; //maximum input boxes allowed
    var min_fields      = 6; //minimum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    var ordertot        = 0;
    var indbrandcost    = 5;
    var shaftprice      = 0;

$(".toproduct, .indmsg").on('keyup keypress blur change paste cut', function(){
        var id28 = 25; //dynamically written based on item price
        var id29 = 50;

//loop through all fields, check if that row exists, then see which selection matches up with id28 or 1d29 above, then do something
        for(i = 1; i < max_fields; i++) { 
            if($('#toproduct'+i).val() != '') {
            var f = $('#toproduct'+i).find('option:selected').attr('value');
                if($('#indmsg'+i).val() != '') {
                    $('#unitprice'+i).text((eval('id'+f)+5).currency()); //getting error here
                    //var shaftprice = shaftprice + indbrandcost;
                }
                else {
                    $('#unitprice'+i).text((eval('id'+f)).currency()); // getting error here
                }
            }

        }

    });

Solution

  • There are a couple of mistakes in your code. I've created a codepen that works: https://codepen.io/pahund/pen/xqpByN?editors=1011

    The relevant code:

    $(".toproduct, .indmsg").on('keyup keypress blur change paste cut', function() {
        var id28 = 25; //dynamically written based on item price
        var id29 = 50;
    
        //loop through all fields, check if that row exists, then see which selection matches up with id28 or 1d29 above, then do something
        for (var i = 1; i < max_fields; i++) {
            var f = $('#toproduct' + i).val();
            if (f) {
                if ($('#indmsg' + i).val() !== '') {
                    $('#unitprice' + i).text((eval('id' + f) + 5)); //getting error here
                } else {
                    $('#unitprice' + i).text((eval('id' + f))); // getting error here
                }
            }
        }
    });
    
    • in your for-look, added a var before the I (otherwise you'll create a global variable window.i
    • using val() to get the value of the dropdown
    • simply checking if variable f is defined instead of testing for an empty string, otherwise you'll try to create a value for a non-existent element topproduct3 (this caused the error “Uncaught ReferenceError: idundefined”)
    • removed the currency plugin from the expression that adds the value to the span with $.text() – the result of this expression is a string, which you cannot run a jQuery plugin on
    • using !== instead of != (best practice, always prefer !== and === to != and ==)