Pooya Mahmoodi Pooya Mahmoodi - 7 months ago 19
Javascript Question

JavaScript for loop

i don't know why my code doesn't run,someone can help me?



<!DOCTYPE html>
<html>
<head>
<title>
excerise
</title>
<style></style>
</head>
<body>


<script>
function multiple ( )
var i=0;
for (i=pooya;i<=5;i++)
{
document.getElementById("pooya").innerHTML = i;
}
}

</script>
number<br>
<input type="text" id="pooya">
<button onclick=" multiple ()">try it</button>
<p>Explanation:</p>

<p>This for loop starts with i=0.</p>

<p>As long as <b>i</b> is less than, or equal to 5, the loop will continue to run.</p>

<p><b>i</b> will increase by 1 each time the loop runs.</p>


</body>
</html>




Answer

The code does not run because of the following issues

function multiple ( ). Though there is a closing } but there is no opening { which mark the start of function body. The function body should be inside { } . Example

function multiple() { //Rest of code}

for (i=pooya;i<=5;i++){}. This part will not work. pooya is a an id to an element & if you are assigning it to a i. If you want to do that initialize pooya with some value

document.getElementById("pooya").innerHTML = i . Are you trying to update the input box? If so then you have to use document.getElementById("pooya").value = i

In this case you will always see 5 as updated value in input box.

If you do document.getElementById("pooya").innerHTML += iyou will see "entered value"+12345; Example:If you give input as4the input box will be updated with4012345`

Check this JSFIDDLE

EDIT

function multiple ( ){
var i= document.getElementById("pooya").value;  // Will take the entered value
document.getElementById("pooya").value=""; // will empty the inpt
for(i;i<=5;i++){ 
 document.getElementById("pooya").value += i; // will update input box

  }
}

Updated jsFidlle