Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
javascript: question about ```.value``` in global/local variable
<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:

  1. x
  2. y
  3. z

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:

  1. x
  2. y
  3. z

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!