简体   繁体   中英

dynamic arrays with input javascript

I am currently doing a school project where I have to use javascript to create a page where a user can key in multiple numbers from an input box.

After each number is entered there is a add button which then shows the number in another box below the input. So each number is displayed vertically down the page.

From there I need two more buttons. The first one to calculate which will add the numbers together and work out the average. The second one will clear the array to start again.

I believe I am ok with the last two buttons. What I am unsure of is how should the user input create the dynamic array which will then be displayed in the page. I have been able to get a single number input but I am missing the next step so the next number entered will dispay and allow me to build an array from which the calculations can be performed.

Easiest way would be to loop over the inputs showing the numbers and add each number that way, rather than trying to maintain an array that is updated from the first input.

Stick the displaying input elements into a container with an id , then you can do something simple like:

var container = document.getElementById("container-id"),
    inputs = container.children,
    total;

for (var x = 0, y = inputs.length; x < y; x++) {
    total += parseInt(inputs[x].value, 10);
}

alert(total) //do something way better than alert!

Please try this I think it will work for you

JAVA SCRIPT :

    <script type="text/javascript">
    var arr = new Array();
    function addNum()
    {
    var temp = document.getElementById('a').value;
    arr.push(temp);
    document.getElementById('a').value = "";
    getAvg();
    }

    function getAvg()
   {
    var sum = 0;
    for(var i = 0; i < arr.length; i++){
        sum += parseInt(arr[i]);
    }

    var avg = sum/arr.length;

    document.getElementById('sum').value = sum;
    document.getElementById('avg').value = avg;


      }

function clearAll()
{
    arr.length = 0;
    document.getElementById('a').value = "";
    document.getElementById('sum').value = "";
    document.getElementById('avg').value = "";
}
</script>

HTML:

       <table>
        <tr><td><input type="text" id="a"></td>
        <td>Sum :<input type="text" id="sum"></td>
        <td>Avg :<input type="text" id="avg"></td></tr>
      <tr><td><input type="button" value="add" onclick="addNum()"></td>
      <td><input type="reset"  value="reset" onclick="clearAll()"></td></tr>

     </table

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