Reputation: 1818
Could anyone please help me sort out a bug in my beginner code? I am trying to add an list item to a list and trying to change the id of what list i'm adding it to in javascript. Thanks in advance.
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("submit");
button.onclick = changeDiv;
}
function changeDiv() {
var counter=1
var name = "ul";
var textInput = document.getElementById("textInput");
var userInput = textInput.value;
alert("adding " + userInput);
var li = document.createElement("li");
li.innerHTML = userInput;
var ul = document.getElementById("ul" + loop());
ul.appendChild(li);
}
function loop() {
return counter;
if (counter==3){
counter==0;
}
counter++;
}
</script>
</head>
<body>
<form id="form">
<input id="textInput" type="text" placeholder="input text here">
<input id="submit" type="button">
</form>
<ul id="ul1">
</ul>
<ul id="ul2">
</ul>
<ul id="ul3">
</ul>
</body>
Upvotes: 0
Views: 92
Reputation: 1598
i think you want is one of these:
counter
to be global (yuk) counter
there counter
into loop()
when you call it.loop()
in changeDiv()
. I think you want #2 though so I fiddled it with several corrections in your code:
The reason that I went with #2 is:
Answer #4 is similar in that it would create a closure for both changeDiv and loop whereby they both have access to what they need. However, I didn't want to change your existing logical blocks too much to stall incremental learning. But one could definitely make an argument for the loop()
(which isn't really a loop but rather a setter) being enclosed in changeDiv()
-- albeit you would likely remove the separate function call at that point and integrate the code more.
Upvotes: 2
Reputation: 24502
Essentially, you need to:
counter
in a global scope (loop()
cannot access it otherwise)loop()
, the return statement must be the LAST thing. Anything after it won't get executed.I altered the logic a bit and the final code is this:
window.onload = init;
var counter=1;
function init(){
var button = document.getElementById("submit");
button.onclick = changeDiv;
}
function changeDiv(){
var name = "ul";
var textInput = document.getElementById("textInput");
var userInput = textInput.value;
var id = "ul" + loop();
alert("adding " + userInput + " to " + id);
var li = document.createElement("li");
li.innerHTML = userInput;
var ul = document.getElementById(id);
ul.appendChild(li);
}
function loop(){
var tmp = counter++;
if (counter==4){
counter=1;
}
return tmp;
}
Note the changes in the loop()
function.
I also altered the changeDiv()
function to display the list ID in the alert.
Upvotes: 0