简体   繁体   中英

Create an array in Javascript using a for loop and HTML inputs

I have indexed a bunch of inputs in my html form.

I want to loop through the inputs and create an array. From that array I want to collect the total (sum) of the fields and finally append another HTML input to display that total.

I know how to do this in PHP but I am struggling with JavaScript and I need it done client side.

I have tried to construct as much of this as possible. Here is a jsFiddle:

Here is my html:

<div style="padding:5px;clear:both;"><input type="text" name="total_inkind" id="total_inkind" placeholder="$" onchange="calcInKind()"></div>

and Javascript:

function calcInKind() {
    var runningTotal = 0;
    var i = 0;
    for (var i = 0; document.getElementById('inkind').value; i++){
        if(document.getElementById('inkind').value != ''){
            $gwyl_gr = document.getElementById('inkind').value;
            $runningTotal = parseFloat($runningTotal) + parseFloat($gwyl_gr);
            }else{
            $gwyl_gr = 0;
            }
            i = i++;
        }
    document.getElementById('total_inkind').value = $runningTotal;
    }

For something as simple as a sum of all the form elements, you don't really need an array unless you want to manipulate every value in more ways than one. You can however loop over every input you had in the form, taking its value and adding it to the total.

Looking at your code however, I have to remark that Javascript does not require variables to be preceded by a $ unlike PHP. You however have the opportunity to use them, which JQuery users often do, to denote that their variable is in fact a JQuery variable.

I forked your JSFiddle and rewrote some things to get it working as the question states: JSFiddle

function sumTheInkinds() {
    var runningTotal = 0;
    var ourlist = document.getElementsByClassName("inkind");
    for (var i = 0; i < ourlist.length; i++) {

        if (ourlist[i].value != '') {
            try {
                runningTotal = runningTotal + parseFloat(ourlist[i].value);
            } catch (err) {
                alert ("Value was not a float!");
            }
        }

    }

    document.getElementById('total_inkind').value = runningTotal;
};
document.getElementById("runcalc").onclick = sumTheInkinds;

My implementation however relies on a button press which may not be intended, which can easily be changed back to onchange by applying this:

var inks = document.getElementsByTagName("inkind"); 
for (var i=0;i<inks.length;i++) {
    inks.onchange = sumTheInkinds;
}

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