表格中类别的总和

时间:2013-06-28 06:28:31

标签: jquery forms html

我试图以另一种形式添加一堆相同的表格。我想我很接近,但我不知道断开的地方。我试图总结表格,然后总结表格中的总数到最后。

HTML

<div class="container">
    <div class="row-fluid">
        <div class "span12  exercise1 addWorkout">
            <img src="assets/img/plus01.jpg" class="addWorkout imgButton">Add A Workout</div>
        <!-- <img src="assets/img/minus01.png" class="delWorkout imgButton"> -->
        <div class="span12 workoutList" id="workoutList">
            <div class="cloneMe">
                <div class="row-fluid exercise1 one_rep_calc_container workoutOrgin span4">
                    <div class="oneWorkout">
                        <form>
                            <div class="span4">Weight
                                <input class="weight" type="number" name="weight" size="2">
                            </div>
                            <div class="span4">Reps
                                <input class="reps" type="number" name="reps" size="2">
                            </div>
                            <div class="span4">OneRepMax
                                <input class="one_rep_max" type="number" Name="oneRepMax" size="2">
                            </div>
                            <div class="span4">TotalWeight
                                <input class="totalWeight" type="number" Name="totalWeight" size="2">
                            </div>
                        </form>
                        <!-- <img src="assets/img/plus01.jpg" class="addWorkout exercise1 imgButton">
 -->
                        <img src="assets/img/minus01.png" class="delWorkout imgButton">
                    </div>
                </div>
            </div>
        </div>
        <div class="span12 workoutResults">
            <form>
                <div class="span4">Total
                    <input class="totalAll" id="subtotal" type="number" name="total" size="2">
                </div>
            </form>
        </div>
    </div>
</div> 

jquery的

$('.totalWeight').change(function () {
    var parent = $(this).parents('.workoutResults .one_rep_calc_container');
    var totalWeight = parseInt(parent.find('.totalWeight').val(), 10);
    var totalAll = parseInt(parent.find('.totalAll').val(), 10);

    if (weight > 0) {
        var totalWeightval = 0;
        $('.totalWeight').each(function () {
            totalWeightval += parseFloat(this.value);
        });
        parent.find('.totalAll').val(totalWeightval);
    } else {
        parent.find('.totalAll');
    }
});

关于我如何更好地组织我的代码的任何建议。

1 个答案:

答案 0 :(得分:0)

var parent = $(this).parents('.workoutResults .one_rep_calc_container');

parents查找与选择器匹配的所有可能的父元素。您应该使用closest代替。


var totalWeight = parseInt(parent.find('.totalWeight').val(), 10);

班级totalWeight有多少输入?一个还是多个?之后您使用$('.totalWeight').each(...),表示会有多个,但parent.find('.totalWeight').val()只有在有一个时才有意义。


if (weight > 0) {

您尚未定义变量weight(除非它是您未显示的全局变量),因此此比较始终为false


parent.find('.totalAll');

这一行本身没有任何用处。