简体   繁体   中英

Sum of input fields in placeholder

Hello i want to find the sum of these input fields and print it in a placeholder of another input.

<input type="text" value="3" name="Value[1][1]">
<input type="text" value="4" name="Value[1][2]">
<input type="text" value="" name="Value[1][3]" placeholder="Sum of previous two">

I want to do it for many inputs for example Value[ x ][ y ] with x -> non specific and y -> specific

This works for the very specific example you provided. Perhaps you can use it as an example to help you solve your problem?

$('[name="Value[1][3]"]').val(
    parseInt($('[name="Value[1][2]"]').val()) + 
    parseInt($('[name="Value[1][1]"]').val())
);

[Edit] Oh right you want to iterate through values of X or Y. Well, the example still stands you can just concatenate you changing y value into the strings being used in the selectors like this:

for(var x = 0; x < 10; x++)
{
    $('[name="Value[' + x + '][3]"]').val(
        parseInt($('[name="Value[' + x + '][2]"]').val()) + 
        parseInt($('[name="Value[' + x + '][1]"]').val())
    );
}

Here is a possible solution:

a) Set the value for 'i' in for loop dynamically so that you can get the total. b) Then, set the total in the last input element.

 var total= 0; for (var i=1; i<=2; i++) { var data = $('input[name="Value[1]['+i+']"]').val(); total+=parseInt(data, 10); } $('input[name="Value[1][3]"]').val(total); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value="3" name="Value[1][1]"> <input type="text" value="4" name="Value[1][2]"> <input type="text" value="" name="Value[1][3]" placeholder="Sum of previous two"> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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