views:

123

answers:

1

Hi guys,

I decided to try and learn more JQuery and here is what I have come up with.

It should be a simple enough job, but I can't get my head around it. I can add it up, but when I change a package, the price just keeps going up. I know I have to add some logic to decrement the counter, too, but I think a fresh pair of eyes would be great.

How would you refactor my code?

Live: http://www.keithdonegan.com/jquery/calculate/

$(document).ready(function()
{
    var bronze = 50;
    var silver = 100;
    var gold = 200;

    var email_support = 20;
    var email_telephone_support = 50;
    var email_telephone_im_support = 80;

    var total_support = 0;
    var total = 0;

    $('#total span').append(total);

    $('input').click(function()
    {
        var input_id = $(this).attr('id');
        switch(input_id)
        {
        case 'bronze': 
            total = bronze;
            $('#total span').empty().append(total = bronze + total_support);
            break;
        case 'silver':
            total = silver;
            $('#total span').empty().append(total = silver + total_support);
            break;
        case 'gold':
            total = gold;
            $('#total span').empty().append(total = gold + total_support);
            break;
        case 'email-support':
            $('#total span').empty().append(total_support = email_support + total);
            break;
        case 'email-telephone-support':
            $('#total span').empty().append(total_support = email_telephone_support + total);
            break;
        case 'email-telephone-im-support':
            $('#total span').empty().append(total_support = email_telephone_im_support + total);
            break;
        default:
            break;
        }
    });
});
+1  A: 

Well, I'm not entirely sure what your plan for this is, but here are some ways to cut this down a few notches in size:

// inside of $input( 'click' )
// Since you are always calling this function, create a reference to it..
var tot_append = $('#total span').empty().append;

//Later
switch(input_id)
{
    case "bronze":
    case "silver":
    case "gold":
        // The above three have the same functional behavior, an eval
        // would be the perfect way to make it all work on one line
        tot_append( eval( "total = total_support + " + input_id ) );
        break;
    case 'email-support':
    case 'email-telephone-support':
    case 'email-telephone-im-support':
        // See above.
        tot_append( eval( "total_support = total + " + input_id ) );
        break;
}

Also, since it looks like you are more or less using the variables total and total_support as parallel incrementers tracking the same value, would it be better to use this instead:

// This would not need a switch at all.
tot_append( eval( "total += " + input_id ) );
Christopher W. Allen-Poole