Simple JS Calculation From MB field Values

Support General Simple JS Calculation From MB field ValuesResolved

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #30956
    @mindspark@mindspark
    Participant

    I have a simple form where I need to multiply 3 the values in 3 fields, and then display the result in a 4th field.

    Field IDs

    Type: Number; ID = "total_number_guards"
    Type: Number; ID = "shift_hours"
    Type: Number; ID = "propposed_rate"

    Type: Number; ID = "proposed_cost" <= This is where I want the calculation to appear

    This is my code - which is not working:

    function updateCost(){
        var n = parseInt(document.getElementById("total_number_guards").value);
        var h = parseInt(document.getElementById("shift_hours").value);
        var r = parseInt(document.getElementById("proposed_rate").value);
        var subtotal = n*h*r;
        document.getElementById("proposed_cost").value=subtotal;
    }

    Any suggestions?

    #30965
    Long NguyenLong Nguyen
    Moderator

    Hi,

    Please refer to this topic https://support.metabox.io/topic/calculation-in-fields-success-error-messages-jquery-version/
    to create a calculation field with jQuery.

    #31019
    @mindspark@mindspark
    Participant

    Thank you Long! I wanted to share my solution.

    my form has 3 fields that receive user inputs, and they are part of a group so they can be cloned:

    Group => group_locations
    Field 1 => shift_hours
    Field 2 => total_number_guards
    Field 3 => proposed_rate

    I added a MB button field to run the calculation

    And display the result in a separate field:

    Total Price => proposed_cost

    
    jQuery(document).on('click', 'button[id^="pricing_group_locations_button_"]', function() {
      console.log('here');
      let wrapper = jQuery(this).closest('.rwmb-group-clone');
      let shift_hours = wrapper.find('input[name<em>="shift_hours"]').val();
      let guards = wrapper.find('input[name</em>="total_number_guards"]').val();
      let proposed_rate = wrapper.find('input[name<em>="proposed_rate"]').val();
      wrapper.find('input[name</em>="proposed_cost"]').val(shift_hours * guards * proposed_rate);
    
    let sum = 0;
      jQuery('input[name*="proposed_cost"]').each(function(index, item){
        console.log(item)
        sum += parseFloat(item.value)
      })
    
    jQuery('#pricing_total_pricing').val(sum);
    });
    
    #31025
    Long NguyenLong Nguyen
    Moderator

    Thanks for sharing the solution.

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.