简体   繁体   中英

How to take the sum of items from a list from a user input

Im trying to have a user input items that get added to a list and then find the sum of all the items in the list. Of course this would only work with numbers and I would have instructions prompting the user to only enter in numbers, but how do I get the sum of items from a list that comes from user input?

My current code only gets the text that the user input types into the text box and then those items get put into a list.

 <!DOCTYPE html> <html> <head></head> <body> <input type='text' id='input' /> <input type='button' value='add to list' id='add' /> <ul id='list'> <li> <b>Topics</b></li> </ul> <script type="text/javascript"> document.getElementById("add").onclick = function() { var text = document.getElementById("input").value; var li = document.createElement("li"); li.innerText = text; document.getElementById("list").appendChild(li); } </script> </body> </html> 

Add it to a variable called sum and use .innerHTML to show the sum on the page.

Since the input is a string, use parseInt() to turn it into a number so that when you add it to sum, it actually adds and doesn't just add the item to the end of sum.

The snippet below works.

 var sum = 0; document.getElementById("add").onclick = function() { var text = document.getElementById("input").value; var li = document.createElement("li"); li.innerText = text; sum += parseInt(text); document.getElementById("list").appendChild(li); document.getElementById("sum").innerHTML = sum; } 
 <!DOCTYPE html> <html> <head></head> <body> <input type='text' id='input' /> <input type='button' value='add to list' id='add' /> <ul id='list'> <li> <b>Topics</b></li> </ul> <h3 id="sum">0</h3> </body> </html> 

You can keep the current sum using the dataset attribute and for each new li update that attribute.

<ul id='list' data-total="0">...</ul>
list.dataset.total = Number(list.dataset.total) + Number(text);

 let list = document.getElementById("list"); let sum = document.getElementById("sum"); document.getElementById("add").onclick = function() { let text = document.getElementById("input").value; let li = document.createElement("li"); li.innerText = text; list.appendChild(li); list.dataset.total = Number(list.dataset.total) + Number(text); sum.textContent = list.dataset.total; } 
 <input type='text' id='input' /> <input type='button' value='add to list' id='add' /> <ul id='list' data-total="0"> <li><b>Topics (<span id='sum'></span>)</b></li> </ul> 

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