开发者

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

I'm working on an calculator that has three fields: "length," "width," "ar开发者_开发问答ea." "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!


Give each input a unique id then:

$('input').change(function() {

var currentId = $(this).attr('id');
if (currentId == 'area'){
//DO AREA CALCULATIONS
}
if (currentId == 'length'){
//DO LENGTH CALCULATIONS
}
if (currentId == 'width'){
//DO WIDTH CALCULATIONS
}

});


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜