I'm making a small game for university and I need to add different shapes in my project. I'm talking about Triangle, Rectangle, Pentagon, Hexagon, Heptagon, Octagon....n-gon. I need all the shapes to be convex regular polygons and being able to color the inside. I'm thinking of drawing SVG shapes, but I'm not sure what the formula should be given only the n-sides of the shape to be generated. If there is a JS plugin that I can just include with Bower and generate the shapes, that will be great. There is also the problem of coloring them and after that being able to change the color with animation, but step by step.
Below is a method I use to build polygons. It provides a random fill color. See if this helps.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create SVG Polygons</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body style='padding:10px;font-family:arial'>
<center>
<h4>Create SVG Polygons</h4>
<div style='width:90%;background-color:gainsboro;text-align:justify;padding:10px;border-radius:6px;'>
Create inline svg with random circles, ellipses, polygons, and rectangles used for test environment.
</div><br />
<div id="svgDiv" style='border:1px black outset'>
<svg id="mySVG" />
</div><br />
Number Of Elements:<input type=text id=elemsValue size=1 value=1200 />
SVG Width:<input type=text id=widthValue size=1 value=600 />
SVG Height:<input type=text id=heightValue size=1 value=400 />
Element Sze:<input type=text id=sizeValue size=1 value=20 />
<button onClick=go()>go</button><br />
<script>
//---button---
function go()
{
var elems=parseInt(elemsValue.value)
var svgWidth=parseFloat(widthValue.value)
var svgHeight=parseFloat(heightValue.value)
var elemSize=parseFloat(sizeValue.value)
//---clear prevoius---
mySVG.removeChild(document.getElementById("globG"))
svgGLOB(elems,svgWidth,svgHeight,elemSize)
}
function svgGLOB(elems,svgWidth,svgHeight,elemSize)
{
/* ---fill empty inline SVG element---
<div id="svgDiv"><svg id="mySVG" /></div>
*/
var NS="http://www.w3.org/2000/svg"
mySVG.setAttribute("width",svgWidth)
mySVG.setAttribute("height",svgHeight)
svgDiv.style.width=svgWidth+"px"
svgDiv.style.height=svgHeight+"px"
var globG=document.createElementNS(NS,"g")
globG.id="globG"
globG.setAttribute("stroke","black")
globG.setAttribute("stroke-width",1)
mySVG.appendChild(globG)
var points=randomPoints(elems,svgWidth,svgHeight,elemSize)
var n=points.length
var circleCnt=0
var ellipseCnt=0
var rectCnt=0
var polygonCnt=0
var RandomElems=[]
RandomElems[0]="circle"
RandomElems[1]="rect"
RandomElems[2]="ellipse"
RandomElems[3]="polygon_3"
RandomElems[4]="polygon_4"
RandomElems[5]="polygon_5"
RandomElems[6]="polygon_6"
RandomElems[7]="polygon_7"
RandomElems[8]="polygon_8"
RandomElems[9]="polygon_9"
RandomElems[10]="polygon_10"
RandomElems[11]="polygon_11"
RandomElems[12]="polygon_12"
for(var k=0;k<n;k++)
{
var rand=rdm(0,12)
var elemStr=RandomElems[rand]
if(!elemStr.indexOf("_"))
var elemSt=elemStr
else
var elemSt=elemStr.split("_")[0]
var elem=document.createElementNS(NS,elemSt)
if(elemSt=="circle")
{
elem.setAttribute("r",elemSize)
elem.setAttribute("fill",rcolor())
elem.setAttribute("cx",points[k][0])
elem.setAttribute("cy",points[k][1])
elem.id=elemSt+(circleCnt++)
}
else if(elemSt=="ellipse")
{
elem.setAttribute("rx",elemSize)
elem.setAttribute("ry",elemSize/2)
elem.setAttribute("fill",rcolor())
elem.setAttribute("cx",points[k][0])
elem.setAttribute("cy",points[k][1])
elem.id=elemSt+(ellipseCnt++)
}
else if(elemSt=="rect")
{
elem.setAttribute("width",elemSize)
elem.setAttribute("height",elemSize)
elem.setAttribute("fill",rcolor())
elem.setAttribute("x",points[k][0])
elem.setAttribute("y",points[k][1])
elem.id=elemSt+(rectCnt++)
}
else if(elemSt=="polygon")
{
var pgonSides=parseInt(elemStr.split("_")[1])
var pgonPnts=polygon(pgonSides,elemSize,points[k][0],points[k][1])
elem.setAttribute("fill",rcolor())
elem.setAttribute("points",pgonPnts.join())
elem.id=elemSt+(polygonCnt++)
}
globG.appendChild(elem)
}
//---obtain a random whole number from a thru b---
function rdm(a,b)
{
return a + Math.floor(Math.random()*(b-a+1));
}
function randomPoints(elems,svgWidth,svgHeight,elemSize)
{
//--return format:[ [x,y],[x,y],,, ]
//---Generate random points---
function times(n, fn)
{
var a = [], i;
for (i = 0; i < n; i++) {
a.push(fn(i));
}
return a;
}
var width=svgWidth-2*elemSize
var height=svgHeight-2*elemSize
return RandomPnts = times(elems, function() { return [Math.floor(width * Math.random()) + elemSize, Math.floor(height * Math.random()) + elemSize] });
}
//---random color---
function rcolor()
{
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ )
{
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
function polygon(vCnt,radius,centerX,centerY)
{
var myPoints=[]
var polyXPts = Array(vCnt);
var polyYPts = Array(vCnt);
var vertexAngle = 360/vCnt;
//---init polygon points processor---
for(var v=0; v<vCnt; v++)
{
theAngle = (v*vertexAngle)*Math.PI/180;
polyXPts[v] = radius*Math.cos(theAngle);
polyYPts[v] = -radius*Math.sin(theAngle);
}
//--note points are CCW---
for(var v=0;v<vCnt; v++)
{
var point=[centerX+polyXPts[v],centerY+polyYPts[v]]
myPoints.push(point)
}
return myPoints
}
}
document.addEventListener("onload",init(),false)
function init()
{
svgGLOB(1200,600,400,20)
}
</script>
</body>
</html>
Related
I made a website which consists of a display area that randomly spawns 50 circular <div> elements. I want to make it so when one of the circles is clicked, it comes to the foreground. I thought using the addEventListener function on each circle as it's created would work but I can't get it to do anything. Thank you.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" type="text/css" href="index_styling.css">
<script type="text/javascript" src="index_scripts.js"></script>
</head>
<header>
<h1>First Last, Assignment #6</h1>
</header>
<div id="orange_strip"></div>
<body>
<form>
<ul>
<li>
<input type="button" name="add" value="Add Square">
<input type="button" name="change" value="Change All Square Colors">
<input type="button" name="reset" value="Reset All Squares">
</li>
</ul>
<div id="display">
</div>
</form>
</body>
<footer>
<div id="copyright">Copyright © 2016 - First Mid Last</div>
</footer>
</html>
JavaScript
window.onload = function() {
for (var i = 0; i < 50; i++) {
var display_div = document.getElementById("display");
var circle = document.createElement("div");
var randNum = getRandomDimension(5000);
circle.setAttribute("class", "circle");
circle.style.backgroundColor = getRandomColor();
circle.style.position = "absolute";
circle.style.left = getRandomDimension(550);
circle.style.top = getRandomDimension(450);
circle.addEventListener("click", bringToFront(circle));
display.appendChild(circle);
}
}
function bringToFront(element) {
element.style.zIndex = "1";
}
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function getRandomDimension(max) {
var num = Math.floor((Math.random() * max) + 1);
var str = num.toString();
return str += "px";
}
This line:
circle.addEventListener("click", bringToFront(circle));
...does not add an event listener. It calls your bringToFront() method immediately and then attempts to assign its return value as a listener except the return value is undefined. (Meanwhile, the effect of calling that function immediately within the loop means all of your divs get set to z-index: 1 upon their creation.)
You should be passing a reference to the function (note there is no () after the function name):
circle.addEventListener("click", bringToFront);
...and then change the function to work with this, because this will automatically be set to the clicked element at the time the function is called for the event:
function bringToFront() {
this.style.zIndex = "1";
}
The problem is with the current line
circle.addEventListener("click", bringToFront(circle));
That is trying to execute the bringToFront function right away.
AddEventListener just needs to function, and it will execute it when the event fires
circle.addEventListener("click", bringToFront);
I have finally managed to create an array of a user's input which match conditions, now I want to make that array into an array that converts all of the user's input into a new array(which is to be grapher later) which consists of the frequency of occurence of all of the users input, it took alot of trouble just finding out how to get an array of the user's input!
Here is the current algorithm which I wanted to change:
function getGraph() {
var i = 0;
var results;
var dicePoss = [1,2,3,4,5,6]
var finished = false;
var newArr ="";
results = document.getElementById('texts').value;
// gets input e.g 623653246325435432156545352516
var resultsArr = results.split("");
//supposed to split input into an array e.g 6,2,3,6,5,3,2,4,6,3,2,5 note commas are invisible and just to show they are an array
document.getElementById('x-axis').innerHTML = dicePoss;
//irrelevant to current algorithm but to be used with x-axis on graph later
while (!finished && i < resultsArr.length) { //while the function is not finished AND the iteration is done 30 times
if (resultsArr[i] <= 6 && resultsArr[i] > 0) { //resultsArr[i] defines the character e.g input 2 currently being iterated in the array
newArr += resultsArr[i] + ","; //adds an element to the new array which is checked to meet the IF statement
i++; //iterates continuously
document.getElementById('y-axis').innerHTML = newArr;
}
else {
finished = true;
}
if (finished == true){
resultsArr = [];
dicePoss = [];
document.getElementById('reject').innerHTML = "Please enter a valid input between 1-6!";
}
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Six Revisions is a blog that shares useful information about web development and design, dedicated to people who build websites." />
<title>6 Sided Die Simulator</title>
<script type="text/JavaScript">
function drawOne(a, n) {
// draws the rectangle for one of the values
// a is a counter for the column
// n is the value being graphed
con.fillStyle = 'red';
con.fillRect(500 + 60 * a, 400, 40, -n);
// write the value below the column
con.strokeText(n, 500 + 40 * a, 440);
}
</script>
</head>
<h1>Six Sided Die Simulator</h1>
<canvas id="myCanvas" width="1200" height="500"style="border:1px solid #FF0000;">Canvas is not supported
</canvas>
<body>
<p id="y-axis">Frequency of die rolls(results)</p>
<p id="x-axis">Dice Possible Rolls between 1-6</p>
<p id="reject"></p>
<input type="text" value="Enter diceroll" id="texts" style="width: 150px;" />
<br />
<input type="button" value="Display Column Graph" onclick="getGraph();">
</body>
</html>
I don't understand the question either but I guess this question can help you. counting-the-occurrences-frequency-of-array-elements
I have finally managed to solve the problem, wondering if anyone can help use the output to draw a column graph with canvas? this is what I can do so far
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Six Revisions is a blog that shares useful information about web development and design, dedicated to people who build websites." />
<title>6 Sided Die Simulator</title>
<script type="text/JavaScript">
function drawOne(a, n) {
// draws the rectangle for one of the values
// a is a counter for the column
// n is the value being graphed
con.fillStyle = 'blue';
con.fillRect(500 + 60 * a, 400, 40, -n);
// write the value below the column
con.strokeText(n, 500 + 40 * a, 440);
}
</script>
</head>
<h1>Six Sided Die Simulator</h1>
<canvas id="myCanvas" width="1200" height="500"style="border:1px solid #FF0000;">Canvas is not supported
</canvas>
<body>
<p id="y-axis">Frequency of die rolls(results)</p>
<p id="x-axis">Dice Possible Rolls between 1-6</p>
<input type="text" value="Enter diceroll" id="texts" style="width: 150px;" />
<br />
<input type="button" value="Display Column Graph" onclick="getGraph();">
<script>
function getGraph() {
var i = 0;
var results;
var dicePoss = [0,1,2,3,4,5,6]
var finished = false;
results = document.getElementById('texts').value;
// gets input e.g 623653246325435432156545352516
var resultsArr = results.split("");
resultsArr.sort();
//supposed to split input into an array e.g 6,2,3,6,5,3,2,4,6,3,2,5 note commas are invisible and just to show they are an array
document.getElementById('x-axis').innerHTML = dicePoss;
//irrelevant to current algorithm but to be used with x-axis on graph later
freq =[0,0,0,0,0,0,0];
var canvas = document.getElementById("myCanvas");
while (!finished && i < resultsArr.length) { //while the function is not finished AND the iteration is done 30 times
if (resultsArr[i] > 0 && resultsArr[i] < 7 ) {//resultsArr[i] defines the character e.g input 2 currently being iterated in the array
freq[resultsArr[i]]++; //adds an element to the new array which is checked to meet the IF statement
i++; //iterates continuously
//commence drawing graph on IF in the while loop
var con = c.getContext("2d");
con.strokeStyle = 'black';
drawOne(dicePoss[i], freq[i])
con.stroke();
document.getElementById('y-axis').innerHTML = freq; //prints on ID the value of function results
}
else {
finished = true;
}
if (finished == true){
//reject message to display in the middle of the graph
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Please enter a valid input between 1 - 6!", canvas.width/2, canvas.height/2);;
}
}
}
//Begin Drawing Graph
var c = document.getElementById("myCanvas");
var con = c.getContext("2d");
con.strokeStyle = 'black';
// move to the bottom left
for(var d=0; d < freq.length; d++)
{
drawOne( dicePoss[d], freq[d])
}
con.stroke();
</script>
</body>
</html>
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**
I have some code in a graph and I already tried this code in canvas but for loop condition based in this code x&y value ellipse shape draw the canvas.
I want to how to add the for loop inside the canvas and plot the ellipse shape.
#mycanvas{
position:absolute;
width:250px;
height:400px;
top:200px;
left:200px;
}
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet"type="text/css" href="newellipse.css">
<script src="jfile/myquery.js"></script>
</head>
<body>
<input id="ipvalue" type="text" value="25x^2+4y^2+100x-40y=-100">
<button onclick="checkFruit()">solve</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px";>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var step = 2*Math.PI/20; // see note 1
var h = 150;
var k = 150;
var r = 80;
ctx.beginPath(); //tell canvas to start a set of lines
for(var theta=0; theta < 2*Math.PI; theta+=step) {
var x = h + r*Math.cos(theta) ;
var y = k - 0.5 * r*Math.sin(theta) ; //note 2.
ctx.lineTo(x,y);
}
ctx.closePath(); //close the end to the start point
ctx.stroke(); //actually draw the accumulated lines
function checkFruit() {
var reg =/([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var equation = id("ipvalue").val();
var spli = reg.exec(equation);
alert(spli);
var y = document.getElementById("ipvalue").value;
switch(y) {
case "25x^2+4y^2+100x-40y=-100":
text = "Formula for Ellipse x^2/a^2+y^2/b^2=1";
text1= "First RHS side value consider for 1";
text2= "LHS side divide by RHS value for 16";
text3= "Take a square root of denaminater value";
text4= "Find the x and y value";
document.getElementById("demo").innerHTML = text;
document.getElementById("demo1").innerHTML = text1;
document.getElementById("demo2").innerHTML = text2;
document.getElementById("demo3").innerHTML = text3;
document.getElementById("demo4").innerHTML = text4;
break;
// add the default keyword here
}
}
</script>
</body>
<html>
<!DOCTYPE HTML>
<html>
<head>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title:{
text: "Try Zooming And Panning"
},
axisY:{
includeZero: false
},
title: {
text: "Graph"
},
data: [{
type: "spline",
dataPoints: [
{ x:-15, y:0 },
{ x:-10, y:18 },
{ x:0, y:20 },
{ x:10, y:18 },
{ x:15, y:0 },
{ x:10, y:-18 },
{ x:0, y:-20 },
{ x:-10, y:-15 },
{ x:-15, y:0 },
]},
]
});
chart.render();
}
</script>
</head>
<body>
<div id="correct"style="position:absolute;width:500px;height:70%;top:80px;left:250px;">
<div id="chartContainer" style="height: 400px; width: 100%;">
</div>
</div>
</body>
</html>
In that modal how to x and y value inside the for loop condition base draw the ellipse graph?
<canvas> must be closed as shown here.
The style attribute on <canvas> must have semicolon (;) before double-quote (").
html
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px;"></canvas>
I personally prefer document.querySelector(...) over document.getElementById(...).
I took liberty to increase the number of lines for ellipsis from 20 to 1000.
My console says ReferenceError: id is not defined. So instead use document.querySelector('#ipvalue').
Also note that .val(...) works but with jQuery. And html uses .value property. So, the code become document.querySelector('#ipvalue').value.
I touched deliberately at your code structure... (I mean the checkFruit(...) function)
<!DOCTYPE HTML>
<html>
<head>
<!--<link rel="stylesheet"type="text/css" href="newellipse.css">
<script src="jfile/myquery.js"></script>-->
<meta charset="UTF-8">
</head>
<body>
<input id="ipvalue" type="text" value="25x^2+4y^2+100x-40y=-100">
<button onclick="checkFruit()">solve</button>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<p id="demo4"></p>
<canvas id="myCanvas"width="578" height="400" style="position:absolute;left:220px;top:50px;"></canvas>
<script>
var canvas = document.querySelector("#myCanvas");
var context2d = canvas.getContext("2d");
var step = 2*Math.PI/1000; // see note 1
var h = 150;
var k = 150;
var r = 80;
context2d.beginPath(); //tell canvas to start a set of lines
for(var theta = 0; theta < 2*Math.PI; theta += step)
{
var x = h + r*Math.cos(theta);
var y = k - 0.5 * r*Math.sin(theta); //note 2.
context2d.lineTo(x,y);
}
context2d.closePath(); //close the end to the start point
context2d.stroke(); //actually draw the accumulated lines
var splitter = /([\-+])?\s*(\d+)?([a-zA-Z])\b/g;
var source = document.querySelector('#ipvalue');
var target = document.querySelector("#demo");
var target1 = document.querySelector("#demo1");
var target2 = document.querySelector("#demo2");
var target3 = document.querySelector("#demo3");
var target4 = document.querySelector("#demo4");
function checkFruit()
{
var equation = splitter.exec(source.value);
console.log('SOURCE: ', source.value);
console.log('EQUATION: ', equation);
console.log('SUGGESTION: ', source.value.match(splitter));
var y = source.value;
switch(y)
{
case "25x^2+4y^2+100x-40y=-100":
var text = "Formula for Ellipse x^2/a^2+y^2/b^2=1";
var text1 = "First RHS side value consider for 1";
var text2 = "LHS side divide by RHS value for 16";
var text3 = "Take a square root of denaminater value";
var text4 = "Find the x and y value";
target.innerHTML = text;
target1.innerHTML = text1;
target2.innerHTML = text2;
target3.innerHTML = text3;
target4.innerHTML = text4;
break;
}
}
</script>
</body>
<html>
So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example