Search code examples
javascriptjquerymatharea

Area calculator with three fields in jQuery (calculate based on missing value)


I'm working on an calculator that has three fields: "length," "width," "area." "Area" is equal to "length" x "width". However, my client needs to ability to update any two of these fields to get the third -- what I currently have only calculates area when length or width changes and doesn't have the ability to calculate the missing value.

jQuery(document).ready( function ($) {
  $('input').change(function() {
    var $parent = $(this).parents("td").children("div").children("div"),
        length = $parent.find('input[id*="field-length-0-value"]').val(),
        width = $parent.find('input[id*="field-width-0-value"]').val();
        $parent.find('input[id*="field-area-0-value"]').val(length * width); 
  });
});

Source, jsbin

How do I make the length or width update when the area is modified?

Many thanks!


Solution

  • Huzzah! I figured it out. Reproducing code below for somebody in a similar situation:

    jQuery(document).ready( function ($) {   
      $('input').change(function() {
        var currentId = $(this).attr('id'),
        $parent = $(this).parents("td").children("div").children("div"),
        lengthId = $parent.find('input[id*="field-length-0-value"]'),
        length = lengthId.val(),
        lengthAtt = lengthId.attr('id'),
        widthId = $parent.find('input[id*="field-width-0-value"]'),
        width = widthId.val(),       
        widthAtt = widthId.attr('id'),
        areaId = $parent.find('input[id*="field-area-0-value"]'),
        area = areaId.val(),
        areaAtt = areaId.attr('id');
    
    
            if ((currentId == lengthAtt) && (area == 0)){
            areaId.val(length * area); //Area when l * w
            }
            if ((currentId == lengthAtt) && (width == 0)){
            widthId.val(area / length); //width when a / l
            }
            if ((currentId == widthAtt) && (area == 0)){
            areaId.val(width * length); //area when w * l
            }
            if ((currentId == widthAtt) && (length == 0)){
            lengthId.val(area / width); //length when a / w
            }
            if ((currentId == areaAtt) && (width == 0)){
            widthId.val(area / length);//width when a / l
            }
            if ((currentId = areaAtt) && (length == 0)){
            lengthId.val(area / width); //length when a / w 
            }
      });
    });
    

    I'm sure there's a few places where it can be optimized...