0

I have a repeater custom meta box for my custom post type. I am new to Javascript and can not figure out how to calculate the value for each repeated input field and display the total combined. I have it functioning for the first input field, but it won't calculate the value of all. Here is the code I am working with.

    <script>
    var $ =jQuery.noConflict();
    $(document).ready(function() {
        var count = <?php echo $c; ?>;
        $(".wpp-item-add.investment").click(function() {
            count = count + 1;
            $('#investment_here').append('<div class="wpp-repeater-wrapper">Title: <input class="wpp-repeater-input" type="text" name="investment['+count+'][title]" value="" placeholder="e.g. Web Design" />Amount: <input class="wpp-repeater-input" id="wpp-amount-value" type="text" name="investment['+count+'][investment_item]" value="" onblur="calculate()" placeholder="e.g. 2500" /><span class="wpp-item-remove investment">Remove</span></div>' );
            return false;
        });
        $(".wpp-item-remove.investment").live('click', function() {
            $(this).parent().remove();
        });
    });
    calculate = function()
    {
    var resources = document.getElementById('wpp-amount-value').value;
    document.getElementById('wpp_investment_total').value = parseInt(resources);

    }
    </script>

Solution I am looking for: If I click Add Item and have 5 input fields, it would calculate the value of each field and have the total go to the field #wpp_investment_total.

HTML Section:

          <div class="wpp-input-container">
              <label class="wpp-label-repeater"><?php _e('Cost Items') ?></label>
              <?php
              wp_nonce_field ( 'c_nonce_field', 'c_wpnonce');
                  $c = 0;
                  if ( count( $investment ) > 0 ) {
                      if(!empty($investment)) {
                          foreach( $investment as $investment_item_val ) {
                             if (!empty($investment_item_val)) {
                              foreach( $investment_item_val as $investment_item ) {
                                  if ( isset( $investment_item['title'] ) || isset( $investment_item['investment_item'] ) ) {
                                      printf( '<div class="wpp-repeater-wrapper">Title: <input class="wpp-repeater-input" type="text" name="investment[%1$s][title]" value="%2$s" />Amount: <input class="wpp-repeater-input" id="wpp-amount-value" type="text" name="investment[%1$s][investment_item]" value="%3$s" onblur="calculate()" /><span class="wpp-item-remove timeline">%4$s</span></div>', $c, $investment_item['title'], $investment_item['investment_item'], __( 'Remove' ) );
                                      $c = $c +1;
                                  }
                              }
                            }
                          }
                      }
                  }
              ?>
              <span id="investment_here"></span>
              <div class="wpp-item-add investment" style="visibility: hidden; margin-bottom: -20px;"><?php _e('Add Item'); ?></div>
              <div class="wpp-item-add investment add-button"><?php _e('Add Item'); ?></div>
              </div>

For anyone looking, here is a working solution by RiddleMeThis

    calculate = function(){
        var total = 0;
        $('.wpp-repeater-input.amount').each(function () {
            total += parseInt($(this).val());
        });
        var discount = document.getElementById('wpp_investment_discount').value;
        var tax = document.getElementById('wpp_investment_tax').value;

        document.getElementById('wpp_investment_total').value = parseFloat(total)+parseInt(discount)+parseFloat(tax);
    }

Current code I have that doesn't subtract value of item deleted

 '<script>
    var $ =jQuery.noConflict();
    $(document).ready(function() {
        var count = <?php echo esc_js( $c ); ?>;
        $(".wpp-item-add.pricing").click(function() {
            count = count + 1;
            $('#pricing_here').append('<div class="wpp-repeater-wrapper">Title: <input class="wpp-repeater-input" type="text" name="pricing['+count+'][title]" value="" placeholder="Web Design" />Amount: <input class="wpp-repeater-input amount" type="text" name="pricing['+count+'][pricing_item]" value="0.00" onblur="calculate()" placeholder="" /><span class="wpp-item-remove pricing">Remove</span></div>' );
            return false;
        });
        $(".wpp-item-remove.pricing").live('click', function() {
            $(this).parent().remove();
        });
    });
    calculate = function(){
        var total = 0;
        $('.wpp-repeater-input.amount').each(function () {
            total += parseFloat($(this).val());
        });

        total = parseFloat(total).toFixed(2);
        document.getElementById('wpp_pricing_total').value = parseFloat(total);
    }
    </script>'
  • Can you post a sample of your HTML? – RiddleMeThis Dec 13 '18 at 16:35
  • Hey RiddleMeThis - I have included the HTML section for you to review! Let me know if you need anything else :) – Kevin W. Dec 13 '18 at 17:07
  • I would suggest not using an ID because as it is now you will have multiple inputs with the same ID. Then you would need to use .each to loop through each one and grab the value. – RiddleMeThis Dec 13 '18 at 17:16
  • Do you have a visual example of how you would set it up? I am fairly new to this and still feel a little confused :/ – Kevin W. Dec 13 '18 at 17:37
  • OK, I added an answer with an example. Let me know how it goes. – RiddleMeThis Dec 13 '18 at 18:42
1

You need to loop through the values of each input and add them together. You can do this using a each.

Try this. Replace your calculate function with this.

calculate = function(){
    var total = 0;
    $('.wpp-repeater-input').each(function () {
        total += parseInt($(this).val());
    });

    document.getElementById('wpp_investment_total').value = parseInt(total);
}

On a side note: I would remove the ID on the input, you shouldn't have multiple of the same IDs. Notice I used the class to target the inputs.

  • Words can't even describe how thankful I am RiddleMeThis! Everything is caculating fine and I was able to add my two extra fields "Discount" and "Tax". The only other think that I wish was different is when I changed it to parseFloat to allow decimals so, for example, $2.50 it displays it as $2.5 instead and it gets rid of the second zero. :/ – Kevin W. Dec 13 '18 at 19:50
  • No Problem! check out - stackoverflow.com/questions/6134039/… If you can't figure it out you should probably open a new question – RiddleMeThis Dec 13 '18 at 19:51
  • Hey RiddleMeThis, I am just about to launch my plugin and as I was testing and debugging before I add it to the WordPress repository, I did notice an issue with the calculate repeaters and was wondering if you would have any ideas on how to fix it. The issue is if someone deletes an item and has a number value in that input field it doesn't subtract that value from the total. The only way to trigger it back to the correct value is to click on one of the other input fields that has the calculate() function assigned to it. I have added the code I currently have to the bottom of the post! – Kevin W. Jan 27 at 18:54
  • Can't you just call calculate() after the delete button is clicked and the element removed? – RiddleMeThis Jan 27 at 19:14
  • You can use a click function on any element. I'm on my phone but if u Google it u can find examples – RiddleMeThis Jan 27 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.