Issue calculating total cost with input fields using jQuery

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>
        <label for="player-division-1">Fee</label>
        <input type="text" id="playerFee1" class="fee" value="" disabled>
    </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>
        <label for="player-division-2">Fee</label>
        <input type="text" id="playerFee2" class="fee" value="">
    </div>
</div>

<div>
    <label for="total">Total</label>
    <input type="text" id="total" value="" disabled>
</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").val(divisions['1'].price);
            break;

            case 7:
            case 8:
                $("#playerDivision1").val(divisions['2'].name);
                $("#playerFee1").val(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").val(divisions['1'].price);
            break;

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

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

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


        });



        $('.fee').keyup(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! :slight_smile:

Because the price is in fields that start with playerFee, such as playerFee1 and palayerFee2, you can tell jQuery to select those fields that start with a certain value:


var total = 0;
$('[id^="playerFee"]').each(function () {
    total += Number(this.value);
});
$('#total').val(total);

Thanks @paul_wilkins! I think I’m getting closer. Only issue now is when I console.log I get [p#playerFee1.fee, p#playerFee2.fee] returned to me. Also my total now says NaN.

Any ideas why that may be?

Thanks again! :slight_smile:

That seems to be giving you the full details about the particular elements, which shouldn’t be a problem.

Let’s see how things go when you provide default value if one can’t be retrieved from a field.


total += Number(this.value) || 0;

It now displays a 0 where the NaN was. It was suggested to me that I eliminate using input fields (which are disabled) so the user can’t change the field and instead use p or span tags with id or class name. Also to replace .val() to .html() as I did below. Does that impact what’s going on here?


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

I did try it but it was affecting ie and I now have it back .val().

Yes it does. When you use HTML it tries to append HTML entities to your target, which won’t work in this case for several reasons.
You need instead to update the value of the input field itself, which is the .val() method.

I’ve adjusted all lines to .val() but you know what the issue ended up being? I wasn’t calling the function to re-calculate the total each time. In fact, I believe it was only calling it once at the very beginning. I’ve added calcFee (); right before each break; and voila…it works.

Thanks for your help Paul! :slight_smile:

		
                 function calcFee () {
			var total = 0;

			$('.fee').each(function(){
					
				var fee = parseFloat($(this).val());
				if (isNaN(fee)) {fee = 0;}
				total += fee;			
										
			});
					
			$('#total').val('$' + total.toFixed(2));		
		};

That’s great. Is there a reason though why the multiple calls to calcFee() can’t brought together to just one after the switch statement?

You’re absolutely right! I placed it just once after each switch statement and still works perfectly. :slight_smile:

I spoke too soon. Works fine in Firefox and Safari but not working in ie at all now. Not even the datepicker. Any thoughts about that?

Not unless it’s possible to check things out in some way, such as with a test page somewhere

If you’re using commands such as console.log, that will cause IE to die in that way. You can go to Tools -> Internet Options -> Advanced and display a notification about every script error, to help you find such problems.