1

I have a function (show below) that totals up all the hours on the page onBlur of the ".total" input fields. This function works perfectly in FF but in Chrome and Safari I am getting this error: SyntaxError: Unexpected EOF ---I did some research but I am lost as to what might be causing this.

thanks for any help!

function totalUpHours() {
    //add all values to an array
    var hrsTotalsarr = new Array();
    $('.total').each(function() {
        var thisTotal = $(this).val();
        //clean the value
        if (thisTotal == "HRS") {
            thisTotal = 0;
        }
        hrsTotalsarr.push(thisTotal);
    });

    //sum up the array
    var hrsTotal = eval(hrsTotalsarr.join('+'));
    $('#taskHRStotals').val(hrsTotal);
}
4

2 回答 2

1

Sometimes invalid characters can work their way into code when you copy/paste code from websites.

Unfortunately, they're often invisible, and can only be noticed if you move your cursor across it with the arrow keys on your keyboard. When you get to the invalid one, the cursor will pause for a single keystroke.


Aside from that, consider this alternative to using eval() in your code.

function totalUpHours() {

    var hrsTotal = $('.total').map(function() {
                                     var thisTotal = $(this).val();

                                     return thisTotal == "HRS" ? 0 : thisTotal;
                                   })
                              .toArray()
                              .reduce(function(total, n) {
                                  return total + n;
                              }, 0);

    $('#taskHRStotals').val(hrsTotal);
}

This is called map/reduce, and is a very handy pattern to know.

于 2012-09-24T20:32:29.213 回答
0

Its seems working. Tested it on chrome.

Refer to the LIVE DEMO for your reference.

HTML:

<input type="text" class="total" value="1" />
<input type="text" class="total" value="2" />
<input type="text" class="total" value="3" />
<input type="text" id="taskHRStotals" value="0" />

JS

totalUpHours();

function totalUpHours(){
    //add all values to an array
    var hrsTotalsarr = new Array();
    $('.total').each(function() {
        var thisTotal = $(this).val();
        //clean the value
        if(thisTotal=="HRS"){
            thisTotal=0;}
        hrsTotalsarr.push(thisTotal);
    });

    //sum up the array
    var hrsTotal = eval(hrsTotalsarr.join('+'));
    $('#taskHRStotals').val(hrsTotal);
}​

​
于 2012-09-24T20:02:16.247 回答