SitePoint Sponsor

User Tag List

Results 1 to 12 of 12
  1. #1
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:

    HTML Code:
    <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:

    PHP Code:
    <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:

    Code JavaScript:
    $(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!

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    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:

    Code javascript:
    var total = 0;
    $('[id^="playerFee"]').each(function () {
        total += Number(this.value);
    });
    $('#total').val(total);
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by metalmonkey View Post
    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]
    That seems to be giving you the full details about the particular elements, which shouldn't be a problem.

    Quote Originally Posted by metalmonkey View Post
    Also my total now says NaN.
    Let's see how things go when you provide default value if one can't be retrieved from a field.

    Code javascript:
    total += Number(this.value) || 0;
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

    Code JavaScript:
    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().

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by metalmonkey View Post
    Also to replace .val() to .html() as I did below. Does that impact what's going on here?
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

    Code JavaScript:
                     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));		
    		};

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by metalmonkey View Post
    I've added calcFee (); right before each break; and voila..it works.
    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?
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You're absolutely right! I placed it just once after each switch statement and still works perfectly.

  10. #10
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    6
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?

  11. #11
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by metalmonkey View Post
    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
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,705
    Mentioned
    101 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by metalmonkey View Post
    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?
    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.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •