views:

121

answers:

3

I write a simple javascript function to display a progressbar with the help of JQuery ProgressBar(http://t.wits.sg/misc/jQueryProgressBar/demo.php#)

The progressBar function can be set to display different background images with different values. I want to display values in [0, MAX*0.3] as red, (MAX*0.3, MAX*0.7] as orange, and (MAX*0.7, MAX] as green. So I write a helper function as follows:

function setBar(bar, cur, total) {
    var v1 = parseInt(total * 0.3);
    var v2 = parseInt(total * 0.7);

    // if I run alert(v1) and alert(v2) here, the values are all right.

    bar.progressBar(cur, {
        max: total,
        textFormat: 'fraction',
        boxImage: '/img/pbar/progressbar.gif',
        barImage: {
            0:  '/img/pbar/progressbg_red.gif',
            v1: '/img/pbar/progressbg_orange.gif',
            v2: '/img/pbar/progressbg_green.gif'
        }
    });
}

The argument cur is the current value while total is the MAX value of the progress bar. The function doesn't seem to work, but when I replace "v1:" and "v2:" with actual values like 50 and 120, the function works well. And I have also checked the value of v1 and v2 before calling bar.progressBar, they are all right.

So the problem seems that I cannot pass a variable instead of a constant to the function bar.progressBar, I think it maybe have relations with javascript argument evaluation order, is there any fix to this problem?

A: 

the problem may be that v1 and v2 are float numbers rather than strings. You are using them as keys on a javascript object.

Try converting them to integers and then to strings if that still doesn't work.

drudru
+6  A: 

try building the object before you pass it:

var barImageObj = {};
barImageObj[0] = '/img/pbar/progressbg_red.gif';
barImageObj[v1] = '/img/pbar/progressbg_orange.gif';
barImageObj[v2] = '/img/pbar/progressbg_green.gif';

bar.progressBar(cur, {
    max: total,
    textFormat: 'fraction',
    boxImage: '/img/pbar/progressbar.gif',
    barImage: barImageObj
});

the problem is that javascript interperets {a:'foo'} and {'a':'foo'} as an object with the string key "a", not with whatever the value of the variable a happens to be

cobbal
It works, many thanks.
ZelluX
+3  A: 

Your problem is in

barImage: {
            0:  '/img/pbar/progressbg_red.gif',
            v1: '/img/pbar/progressbg_orange.gif',
            v2: '/img/pbar/progressbg_green.gif'
        }

When using the object literal form, the element names are taken as literals, i.e the fact that v1 and v2 are variables has no effect, the object you created has elements 0, 'v1' and 'v2'.

To do what you want you need

barImage = { };

barImage[0] = '/img/pbar/progressbg_red.gif';
barImage[v1] = '/img/pbar/progressbg_orange.gif';
barImage[v2] = '/img/pbar/progressbg_green.gif';
Hans B PUFAL