Summarize a list of text fields in jQuery

I have a form in which there are text fields added dynamically using jquery. Text field identifiers are formed as an array, that is, the number [0], the number [1], the number [2] ...

I want to add numbers to these text fields and display the value in another text field named "total_quantity", preferably when the focus is shifted from the text field of the array.

How can i do this? I don't mind using jQuery or plain javascript, which is ever easier.

+3
source share
3 answers

I would suggest giving a common class to your fields so that:

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

Then you can define the following function using 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);
}

onblur , . , calculateTotal().


, $("input[id^='Quantity[']"), Felix . , : Quantity[

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

Use the following function if document.getElementsByName () cannot be used, as some MVC frameworks, such as Struts and Spring MVC, use the name attribute to bind an element to an internal object.

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;
}
0
source

Source: https://habr.com/ru/post/1730747/


All Articles