简体   繁体   English

在jQuery中汇总文本框列表

[英]Sum a list of text boxes in jQuery

I have a form in which there are textbox(s) added dynamically using jquery. 我有一个表单,其中有使用jquery动态添加的文本框。 The textbox ids is formed as an array, ie Quantity[0], Quantity[1], Quantity[2] ... 文本框ID形成一个数组,即Quantity [0],Quantity [1],Quantity [2] ......

I want to add the numbers in these textbox(s) and display the value in another textbox named "total_quantity" preferably when the focus is shifted out of the array textbox. 我想在这些文本框中添加数字,并在另一个名为“total_quantity”的文本框中显示该值,最好是在焦点移出数组文本框时。

How can I do it? 我该怎么做? I dont mind using jQuery or plain javascript, which ever is easier. 我不介意使用jQuery或简单的javascript,这更容易。

I would suggest giving a common class to your quantity fields such that: 我建议为您的数量字段提供一个公共类,以便:

<input type="text" class="quantity" onblur="calculateTotal();" />

Then you would be able to define the following function with jQuery: 然后你就可以用jQuery定义以下函数:

function calculateTotal() {
    var total = 0;

    $(".quantity").each(function() {
        if (!isNaN(this.value) && this.value.length != 0) {
            total += parseFloat(this.value);
        }
    });

    $("#total_quantity").val(total);
}

The onblur event will fire each time the focus is shifted from the quantity fields. 每次焦点从数量字段onblur事件将触发。 In turn, this will call the calculateTotal() function. 反过来,这将调用calculateTotal()函数。


If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. 如果您不想添加公共类,可以使用$("input[id^='Quantity[']")选择器,正如Felix在下面的注释中所建议的那样。 This will match all the text boxes that have an id starting with: Quantity[ 这将匹配所有ID开头的文本框: Quantity[

var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);

Use the following function, if one can't use document.getElementsByName(), as some MVC frameworks such as Struts and Spring MVC use the name attribute of a text to bind the element to a backend object. 如果不能使用document.getElementsByName(),请使用以下函数,因为某些MVC框架(如Struts和Spring MVC)使用文本的name属性将元素绑定到后端对象。

function getInputTypesWithId(idValue) {
    var inputs = document.getElementsByTagName("input");
    var resultArray = new Array();

    for ( var i = 0; i < inputs.length; i++) {
        if(inputs[i].getAttribute("id") == idValue) {
            resultArray.push(inputs[i]);
        }
    }
    return resultArray;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM