Mike Spider Mike Spider - 2 months ago 14
Javascript Question

Object property lost in loop

I'm working with the local storage for the first time and going through some JS tutorials online as I'm quite rusty. Making a dictionary where you can add words in 2 idioms then it displays. Everything is working fine with the exception of the second item in the object "dict", is not being shown although it's in the object. it shows in the console output. Might be the indexing in the loop. Cannot see it though. Any light shed will be appreciated.

function getDictionary(){
var dict = {},
dictStr = localStorage.getItem('dictionary');

if(dictStr !== null){
dict = JSON.parse(dictStr);
}


return dict;

}


function show(){
var html = "";
var resultOutput = document.getElementById("resultOutput");
var dict = getDictionary();
for(var i = 0; i < Object.keys(dict).length; i++){
key = Object.keys(dict)[i];
html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key +
" </span>in portuguese is <span style='color: green'> " + dict[key]+
"</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";

resultOutput.innerHTML = html;


var buttons = document.getElementsByClassName('removeBtn');
for(var i = 0; i < buttons.length; i++){
buttons[i].addEventListener('click',remove);
}



}

console.log("");
console.log("All words: "+ JSON.stringify(dict));


}


HTML
...


<p id="sayHello"></p>

<fieldset id="translateField">
<legend> Translate english to Portuguese</legend>
<input type="text" id="newWordEng" name="newWordEng" value="" placeholder=" write the english word" >
<input type="text" id="newWordPt" name="newWordPt" value="" placeholder=" write the portuguese word">
<input type="button" id="addWordBtn" name="addWordBtn" value="Add New Word">
</form>

</fieldset>

<div id="resultOutput">
</div>


<script src="src/translate.js"></script>
</body>

Answer

I think it's because you're using the variable "i" twice. In the inner for loop, try using "j" instead:

for(var j = 0; j < buttons.length; j++){
        buttons[j].addEventListener('click',remove);
}

Edit: In fact, you can probably remove the inner loop altogether, and just do:

function show(){
    var html = "";
    var resultOutput = document.getElementById("resultOutput");
    var dict = getDictionary();
    for(var i = 0; i < Object.keys(dict).length; i++){
        key = Object.keys(dict)[i];
        html += "<p class='normal-paragraph'>The english word <span style='color: green'> " + key + 
                " </span>in portuguese is <span style='color: green'>  " + dict[key]+
                "</span> <button class='removeBtn' id='"+ i +"' >x</button></p>";

        resultOutput.innerHTML = html;

        var buttons = document.getElementsByClassName('removeBtn');
        buttons[i].addEventListener('click',remove);
    }
}