0

Can someone tell me where I'm going wrong here? I want the functionality of the first piece of code to work with an "onclick" function call.

<html>
    <body>
        <h1>Global variables</h1> 
        <p id="before">Something should print here</p>
        <p id="after">Something should print here</p>

    <script>
        x = 0;
        document.getElementById("before").innerHTML = x;
        day();
        function day() {
        x = 5;
        }
        document.getElementById("after").innerHTML = x;
    </script>
    </body>
</html>

I can't get this to work properly. According to w3schools: "If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable".

<html>
    <body>
        <h1>Global variables</h1> 
        <div id="buttons">
            <button id="5" onclick=day(this.id)>Click me to find out the ID!</button>
        </div>
        <p id="test">Something should print here</p>

    <script>
        function day(id) {
            x = id;
        }
        document.getElementById("test").innerHTML = x;
    </script>
    </body>
</html>

This modified w3schools code demonstrates my problem:

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Scope</h2>

<p>carName within myFunction() and outside myFunction are distinct.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
carName = "Toyota";
myFunction();

function myFunction() {
  var carName = "Volvo";
  document.getElementById("demo1").innerHTML = "This variable - " + carName + " is defined within the function";
}
document.getElementById("demo2").innerHTML = "This variable - " + carName + " is defined outside the function";
</script>

</body>
</html>
mich-ish
  • 48
  • 9

2 Answers2

0

You need to move the innerHTML assignment into the day() function.

<script>
   var x;
   function day(id) {
   x = id;
}
document.getElementById("test").innerHTML = x;
</script>
Ozgur Sar
  • 2,067
  • 2
  • 11
  • 23
  • Hi ozgur, the problem is I want the x variable in the function to be a global variable. – mich-ish Nov 14 '20 at 13:11
  • Sorry @mich-ish, I misunderstood the problem – Ozgur Sar Nov 14 '20 at 13:14
  • @mich-ish I edited my answer that declares the x variable as a global variable. I tested and it works. – Ozgur Sar Nov 14 '20 at 13:21
  • hmm this won't work for me. according to this link it shouldn't either... https://www.w3schools.com/js/tryit.asp?filename=tryjs_scope_local – mich-ish Nov 14 '20 at 15:31
  • I moved x decleration outside the function day()'s scope in order to define it in the global scope (as per your request). – Ozgur Sar Nov 14 '20 at 16:13
  • I added some code at the bottom that shows that declaring a variable outside a function does not affect the variable inside the function and vice versa. – mich-ish Nov 14 '20 at 17:24
0

It is generally not a good idea to use inline event handling (onclick=... within html).

You can use an event handler for the button that prints the value of the button id. See also ...

Something like:

let id4, id5, id6;

// It may be better to lessen 'pollution of the global scope'
// e.g. by assigning the value to properties of one object
// https://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted
let myVariables = { id4: null, id5: null, id6: null };

// add event listener
document.addEventListener("click", clickHandling);

function clickHandling(evt) {
//                     ^ event is sent automatically on event occurence
  const origin = evt.target;
//               ^ evt.target returns the element the event originated from
  if (origin.nodeName === "BUTTON") {
//                        ^ only do stuff when the origin is a button  
    const numericId = Number(origin.id.replace(/[^\d]/g, ""));
//                                  ^ retrieve only numeric value(s) from id
    window[`id${numericId}`] = +numericId;
//  ^ a global variable is actually a property of 'window',
//    so, you can  assign a value to that
    myVariables[`id${numericId}`] = +numericId;
//  ^ same, but now use 'myVariables' object                 
    console.clear();
    console.log(`id${numericId} = ${
      window[`id${numericId}`]} and myVariables.id${numericId} = ${
        myVariables[`id${numericId}`]}`);
//  ^ show the assigned values in the console

    document.querySelector("#test").textContent = `My id is ${origin.id}`;
//                                  ^ print button id value to p#test
  }
}
<div id="buttons">
  <button id="b_4">Click me to find out the ID!</button><br>
  <button id="b_5">Click me to find out the ID!</button><br>
  <button id="b_6">Click me to find out the ID!</button>
</div>
<p id="test">Something should print here</p>
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • Thanks Kooilnc. Do you know how I might deal with the global variable issue? Really what I want is to return the id as a global variable so that I can use it as an index elsewhere in the script. – mich-ish Nov 14 '20 at 13:25
  • You can assign a value to a global value, which is actually a property of `window` (the global scope of the browser). See updated code – KooiInc Nov 14 '20 at 13:40
  • Thanks Kooilnc. This is quite different from my original code and it's a good bit to take in as a JS beginner. – mich-ish Nov 14 '20 at 15:34
  • Don't use ``window[`id${numericId}`]``. Use a global array (or object) and store the values in there. – Bergi Nov 14 '20 at 17:49