3

I have a form in which there are textbox(s) added dynamically using jquery. The textbox ids is formed as an array, i.e. 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.

How can I do it? I dont mind using jQuery or plain javascript, which ever is easier.

3 Answers 3

8

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:

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. In turn, this will call the calculateTotal() function.


If you prefer not to add a common class, you can use the $("input[id^='Quantity[']") selector, as Felix suggest in the comment below. This will match all the text boxes that have an id starting with: Quantity[

Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do it if i dont want to use class but the id is like item[0]_Quantity, item[1]_Quantity. In this case i cannot use starts with because some other fields starts with the same eg: item[0]_name
1
var Total = 0;
$("input[id^='Quantity[']").each(function() { Total += $(this).val()|0; });
$("#total_quantity").val(Total);

Comments

0

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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.