I’ve started javascript just today and done my research about this matter around the web. But I couldn’t get the hang of the usage of closures, especially for this code I’ve written:
function writeit()
{
var tbox = document.getElementById('a_tbox').value;
var letters = tbox.split("");
for(var i=0;i<letters.length;i++)
{
if(letters[i]==="a")
{
document.a_form.b_tbox.value = i+1 + ". character is a";
}
else if(letters[i]==="b")
{
document.a_form.b_tbox.value = i+1 + ". character is b";
}
else
{
document.a_form.b_tbox.value = i+1 + ". character is not a nor b";
}
}
}
As you see here, I’d like to get a string from a text box, split it to an array and change the values inside it by using a for loop. What I expect from my code is, if the text box contained “abc” as a user contribution, the output would be “1. value is a 2. value is b 3. value is not a nor b”. But it only gives “3. value is not a nor b” as an output. What can be done to prevent this problem?
Each iteration of your loop is overriding the last result since you are replacing the value of the textbox rather than adding on for each iteration. Use += to avoid this, like so: