jQuery 求和动态生成的输入值无效

jQuery sum dynamically generated input values not working

Whosebug 的好朋友们好!我有一个小问题,过去两天一直在努力解决它...

故事部分:

我有通过按钮动态生成(并删除)的输入。输入被编程为使用 google API 自动完成功能。沿着这一行我还有另一个框,用于存储两个输入(从,到)之间的距离(以千米为单位)。自动完成、添加、删除、距离计算器非常有用。问题是将“.distance”结果输入中的值添加到页面底部的总计输入中。基本上,我想计算总行驶距离。我的代码只输出总计的初始值,即“0”。尝试 parseFloat 将 return 一个 NaN。

代码部分:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    function addAutocompleteToField($field) {
        var autocomplete = new google.maps.places.Autocomplete($field[0], { types: ['geocode'] });

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            $field.change();
        })
    }
    //<![CDATA[
    var map = null;
    var directionsService = new google.maps.DirectionsService();

    function computeTotalDistance(result) {
        var total = 0,
            myroute = result.routes[0];
        for (i = 0; i < myroute.legs.length; i++) {
            total += myroute.legs[i].distance.value;
        }
        return total;
    }

    function calcRoute($row){
        driveDistance = 0;
        rate = 0;
        taxes = 0;
        lastmo =  $('.lastmonth').val();
        var start = $row.find('.from').val();
        var end = $row.find('.to').val();
        var request = {
            origin : start,
            destination : end,
            travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                distance = computeTotalDistance(response);
                select = $row.find('.driveType').children('.option').filter(' :selected').val();
                if (select === "One way") {
                    driveDistance = formatDistance();
                    $row.find('.total input[type="hidden"]').val(distance).change();
                    $row.find('.distance').html(driveDistance);
                }
                else
                {   driveDistance = 2 * formatDistance();
                    $row.find('.total input[type="hidden"]').val(distance * 2).change();
                    $row.find('.distance').html(driveDistance);
                    taxes = taxes * 2;
                }
                if (lastmo < 20000)
                {
                    rate = 3.73;
                }
                else
                {
                    rate = 2.10;
                }
                taxes = driveDistance * rate;
                $row.find('.taxes').html(Math.floor(taxes));
                // Find the .distance element and put the text inside it
            }
        });
    }


    function calcTaxes($row) {
        totaDriveDistance = 0;
        $row.find('.distance').each(function(){
        totalDriveDistance = driveDistance;
        })
    }

    function calcTotals($row){
        var total = 0;
        $row.find('.distance').each(function(){
            total += +($(this).val());
        });
        $(".totalkm input").val(total.toFixed(2));
    }




    function formatDistance(distanceInMeters) {
        distanceInMeters = Math.floor(distance / 1000);
        return distanceInMeters;
          }

    // Add autocomplete functionality to a single row
    function addRowEvents($row) {
        $row
            .find('.autocomplete').each(function () {
                addAutocompleteToField($(this));
            }).end();
    }

    $(function() {
        $('.row-container')
            .on('change', '.autocomplete', function() {
                calcRoute($(this).closest('.row-holder'));
            })
            .on('change', '.driveType', function() {
                calcRoute($(this).closest('.row-holder'));
            })
            .on('change', '', function() {
                calcTaxes($(this).closest('.row-holder'));
            })
            .on('change', '.total', function() {
                calcTotals($(this).closest('.row-holder'));
            });

        $('.row-container .row-holder').each(function() {
            addRowEvents($(this));
        });
        var max = 50;
        var count = $('.row-holder').length;
        $(document).on("click", ".add" ,function() {
            // Generate a new row with the maximum limit of 50
            if (count <= max)
            {
                var $newRow = $($('.example-row').html());
                // add autocomplete to the new row
                addRowEvents($newRow);
                $('.row-container').append($newRow);
                count++;
            }
        });


        $(document).on("click", ".remove", function () {
            // Delete current row whitout deleting all of them (the first one remains at all times)
            if (count > 2) {
                $(this).parent().remove();
                count--;
            }
        });
    });


</script>
<legend><span class="glyphicon glyphicon-wrench"></span><strong>CREATE MILEAGE REPORT</strong></legend>
<input name="lastMonth" class="lastmonth form-control" type="text" placeholder="Last month mileage count" style="width: 20%;margin-bottom: 10px" />

<?php
    function renderRow() {
        return <<<HTML
<div class="row-holder form-inline form-group">
    <button type="button" name="remove[]" class="remove btn btn-danger"><span class="glyphicon glyphicon-remove"></span></button>
    <input name="date[]" class="date form-control" type="text" placeholder="Date" style="width: 10%" />
    <input name="from[]"  class="autocomplete from form-control" type="text" placeholder="From..." />
    <input name="to[]"  class="autocomplete to form-control" type="text" placeholder="To..." />
    <input name="purpose[]" type="text" class="form-control" placeholder="Purpose" />
    <select name="drivetype[]" class="form-control driveType" style="width: 10%;display: inline"><option class="option" value="One way">One Way</option><option class="option" value="Two way">Two Way</option></select>
    <div class="total form-control">
        <input type="hidden" name="distance[]" />
        <span style="width: 100%" class="distance"></span> Km
    </div>
    <div class="totalkr form-control">
        <input type="hidden" name="totalkr[]" />
        <span style="width: 100%" class="taxes"></span> Kr
    </div>
</div>
HTML;
    }
?>


<div class="row-container">
    <?php echo renderRow() ?>
</div>
<button type="button" class="add btn btn-success">
    <span class="glyphicon glyphicon-plus"></span>
    Add new mileage entry
</button>


<div class="hidden example-row">
    <?php echo renderRow() ?>
</div>
<legend style="margin-top:20px"></legend>
<legend style="padding-bottom: 20px"></legend>
<span class="totalkm"><input type="text" value="" name="Total" placeholder="Total:" /></span>

<button type="button" style="float:right;margin-right:1%" class="btn btn-info">Save to table</button>

啊,一个 link 到 phpfiddle:http://phpfiddle.org/main/code/18tf-a8gb 任何帮助深表感谢! 祝你好运。

我有一些问题可以使用一些技巧解决

dist_val = $(this).text();
total +=  parseFloat(dist_val.toFixed(2));

希望这能解决您的问题