3

I've been searching online for a solution to my problem but no luck yet. I'm hoping someone will be able to get me past this obstacle I've hit or point me in the right direction.

I'm creating an online registration form for players. So far, when I select a birth date using jquery's datepicker, it will return the correct age of the user based on the specific date I've set. I'm using a switch statement to display the correct division name and price value on the webpage based on the age selected.

All seems to work correctly up to this point.

My problem now is that I cannot seem to target the value of each price in order to create a function that adds up each price for a grand total.

HTML portion taken from my php file:

<div>
    <div>
        <label for="player-birthdate-1">Birthdate</label>
        <input type="text" class="default-input" id="datepicker1" value="">
    </div>

    <div>
        <label for="player-division-1">Division</label> 
        <input type="text" id="playerDivision1" value="" disabled> 
    </div>

    <div>
        <p id="playerFee1" class="fee" value=""></p>
    </div>
</div>


<div>
    <div>
        <label for="player-birthdate-2">Birthdate</label>
        <input type="text" class="default-input" id="datepicker2" value="">
    </div>

    <div>
        <label for="player-division-2">Division</label> 
        <input type="text" id="playerDivision2" value="" disabled> 
    </div>

    <div>
        <p id="playerFee2" class="fee" value=""></p>
    </div>
</div>

<div>
    <p id="total" value=""></p>
</div>

Portion taken from my php file where I'm grabbing the division name and price from the database:

<script>
    var divisions = {
        <?php
    $sql = $db->prepare("SELECT * FROM division");
    $sql->execute();
    $results = $sql->fetchAll(PDO::FETCH_OBJ);

    foreach ($results as $division) :
        ?>

            '<?php echo $division->division_id; ?>' : {
           id : '<?php echo $division->division_id;?>'
          ,name : '<?php echo $division->division_name;?>'
          ,price : '<?php echo $division->division_price;?>' 
            },

        <?php endforeach; ?>
    }
</script>

Datepicker and Total Fee code taken from my js file:

$(document).ready(function() {

    $( '#datepicker1' ).datepicker({
onSelect: function(value, ui) {
    var newDate = new Date("April 30, " + (new Date()).getFullYear()),
        dob = $("#datepicker1").datepicker("getDate"),
        age = new Date(newDate - dob).getFullYear() - 1970;
        $('#age').val(age);
        console.log(age);

        switch (age){

            case 5:
            case 6: 
                $("#playerDivision1").val(divisions['1'].name);
                $("#playerFee1").html(divisions['1'].price);
            break;

            case 7:
            case 8: 
                $("#playerDivision1").val(divisions['2'].name);
                $("#playerFee1").html(divisions['2'].price);
            break;

                            //continues on for the remaining of the ages.....

                },                      
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd', 
                yearRange: '1990:2012'


        });


    $( '#datepicker2' ).datepicker({
onSelect: function(value, ui) {
    var newDate = new Date("April 30, " + (new Date()).getFullYear()),
        dob = $("#datepicker1").datepicker("getDate"),
        age = new Date(newDate - dob).getFullYear() - 1970;
        $('#age').val(age);
        console.log(age);

        switch (age){

            case 5:
            case 6: 
                $("#playerDivision2").val(divisions['1'].name);
                $("#playerFee2").html(divisions['1'].price);
            break;

            case 7:
            case 8: 
                $("#playerDivision2").val(divisions['2'].name);
                $("#playerFee2").html(divisions['2'].price);
            break;

                            //continues on for the remaining of the ages.....

                },                      
                changeMonth: true,
                changeYear: true,
                dateFormat: 'yy-mm-dd', 
                yearRange: '1990:2012'


        });


    $('.fee').html(function(){

        var total = 0;

        $('.fee').each(function(){

            var fee = parseFloat($(this).val());
                        if (isNaN(fee)) {fee = 0;}
                        total+= fee;

            $('#total').html('$' + total);

        });
    });

});

I look forward to advice from those on the forum. Any help or push in the right direction is greatly appreciated! :)

warr0032
  • 135
  • 1
  • 1
  • 7
  • what is the current behavior of the code? – driangle Feb 04 '12 at 20:07
  • Check this http://stackoverflow.com/q/2417553/1164491 – Cheery Feb 04 '12 at 20:26
  • @ggreiner - Are you referring to what currently happens when I select the birth date? If so, it displays the division name and price in separate input text fields. My issue is I'm not properly targeting the value so that I may add the prices together for a total. Seems to display but useless when it comes to using it to add. – warr0032 Feb 04 '12 at 20:52

3 Answers3

2

You've done a nice job and made it easy by giving each one a class of "fee" already, but I assume you want to parseFloat the number, not parseInt (in case there's cents in the fee?).

Also, you need to check if it's isNaN (not a number), otherwise it won't work properly. That's a simple matter of adding:

if (isNaN(fee)) {fee = 0;}

Finally, it appears that you're doing it on the "change" event. I've had better luck with the keyup event.

random_user_name
  • 25,694
  • 7
  • 76
  • 115
  • Thanks @cale_b. That makes complete sense to use parseFloat seeing as its a price. I did change my code to try your suggestions but it doesn't seem to fix the issue yet. I think it's that I'm not properly targeting the value in order to add the prices. – warr0032 Feb 04 '12 at 20:51
  • If you use Firefox, you can add a line to see if it's picking it up: console.log(fee); - the console log is visible through the Error Console. – random_user_name Feb 04 '12 at 22:06
  • I tried to console.log but it doesn't appear as it registers (fee). Somewhere along the line I'm losing the value of each .fee – warr0032 Feb 04 '12 at 22:57
  • Sorry, I meant doesn't appear to register (fee). – warr0032 Feb 04 '12 at 23:04
  • What is a potential value of fee? Can you share exactly what one of the input boxes might contain for a value? – random_user_name Feb 04 '12 at 23:08
  • Each input box should contain the price associated with the age selected. It seems to display it properly on the page by using $("#playerFee1").val(divisions['1'].price); depending on what age the player is. From there I'd like to total for each. Maybe I'm missing a step altogether. – warr0032 Feb 04 '12 at 23:16
  • Now I see - those inputs are disabled. That is the issue. If you cannot edit the price, why not change the inputs to span/p tags, and update the price using the .html() method? Then you could roll through them, same concept, and just get the contents using $(".fee").html() – random_user_name Feb 05 '12 at 00:14
  • Thanks for that last post. I edited the changes above. I'm getting closer. :) At least now it's showing up as $0 on the screen for the total but displaying NaN when I console.log(fee) within the function. – warr0032 Feb 05 '12 at 01:28
0

I think what's happening is the line (and it's code):

$('.fee').html(function(){

is never actually being called or it's not being called at the right time.

My suggestion would be to wrap the contents of the .fee stuff in a function. Then call that function in the date picker's select callback. (Probably right before every break; statement.) This way the total would be recalculated every time the date changes.

Your function would look something like this:

function calcFee () {
  var total = 0;

  $('.fee').each(function () {
    ...
  });
}
Thomas J Bradley
  • 13,726
  • 3
  • 18
  • 8
  • You were absolutely right. It was calling the function just once at the beginning but not responding each time the date was changed. Thank you very much! – warr0032 Feb 05 '12 at 23:24
  • I should add that I placed it after each switch statement and that works as well. – warr0032 Feb 05 '12 at 23:50
0

If you are doing the calculations inside the jQuery each() function loop then you can use the jQuery $(this).val() to grab the value inside each box. Then you can create a cumulative total.

Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72