<html>
<head>
<title>Example 1</title>
</head>
<body>
<input type="text" id="item">
<br>
<input type="button" value="add item" onclick="addItem()">
<br>
<div id="output"></div>
<script>
var html = '';
var output = document.getElementById('output');
var number = 0;
function addItem(){
var shoppingList = [];
var item = document.getElementById('item').value;
shoppingList.push(item);
html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
output.innerHTML = output.innerHTML + html;
}
</script>
</body>
</html>
When I add x, y, z to shoppingList in the above first example, I receive:
which is that, what I want to receive.
When var item becomes global in the below second example:
<script>
var html = '';
var output = document.getElementById('output');
var item = document.getElementById('item').value;
var number = 0;
function addItem(){
var shoppingList = [];
shoppingList.push(item);
html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
output.innerHTML = output.innerHTML + html;
}
</script>
I receive:
1. 2. 3.
So when I move .value from var item to shoppingList.push(item) in the below third example:
<script>
var html = '';
var output = document.getElementById('output');
var item = document.getElementById('item');
var number = 0;
function addItem(){
var shoppingList = [];
shoppingList.push(item.value);
html = (number = (number + 1)) + '. ' + shoppingList + '<br>';
output.innerHTML = output.innerHTML + html;
}
</script>
I receive:
Would you Guys be able to explain, why I have to move .value from var item to shoppingList.push(item), if I want to receive the output from the third example (1. x
2. y
3. z), if var item is global, please?