【问题标题】:count the textbox values using javascript使用javascript计算文本框值
【发布时间】:2011-08-13 02:15:00
【问题描述】:

我已经使用javascript动态添加了行。现在我必须对文本框中的值求和。如果我单击添加按钮,将添加同一行。现在我有一个固定的文本框。如果我在文本框中输入值它应该添加并显示在 keypress 上的固定文本框中。我如何使用 javascript 或 jquery 来做到这一点

这是我添加行的 html 和 jquery 脚本

输入 id="name" type="text" 输入 id="add" type="button" value="+" 输入 id="Button1" type="button" onclick="removeRowFromTable();"值="x"

我使用 jquery 动态添加行,使用 javascript 删除行

$(document).ready(function() 
{
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');

$('#mytable tbody>tr:last #name').val('');
$("#mytable tbody>tr:last").each(function() {this.reset();});      
return false;
return false;
    });
});

函数 removeRowFromTable() { var tbl = document.getElementById('mytable'); var lastRow = tbl.rows.length; if (lastRow > 2) tbl.deleteRow(lastRow - 1); }

【问题讨论】:

  • 你有没有尝试过?你应该...

标签: javascript jquery


【解决方案1】:

这是我使用 jQuery 编写的一个快速插件。

$.fn.sum = function(settings) {

    settings = jQuery.extend({
        name: "sum",
        global: true
    }, settings);

    var total = 0.0;
    this.each(function() {
        var item = parseFloat($(this).val());
        if (isNaN(item)) item = 0;

        total += item;
    });
    return total;
};

然后连接你的添加按钮

$('.add').click(function() {
     $('.total').html($('.rowTotal').sum());
});

【讨论】:

    【解决方案2】:

    如果您使用可预测的命名方案添加行,您只需遍历控件,找到文本框并确保名称符合您的方案。由于这是一个“添加数字”功能,因此您还需要附加一个不允许在框中只包含数字的功能,否则会出错。

    如果命名不可预测,和/或您只使用文本框作为数字,您可以通过查找所有文本框控件来简化。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2021-10-07
      • 2014-02-09
      相关资源
      最近更新 更多