0

I want to use switch by using HTML buttons. I have 3 buttons, tried for now only with the first button. I gave it id=1, and once clicked it should pass value 2 to function switchProduct() which will use case:2 however, once the page loaded, the function is executing:

console.log('Apples are $0.32 a pound.') - 

okay so I didn't even press the button, and it has passed value to switch once the page loaded, and when I pressing the button it's simply not working (it is not console logging anymore), it's just one time run function - how to fix it? I want to use buttons how many times I need.

script.js

let bttn = document.getElementById("1");
bttn.addEventListener("click", switchProduct(2));

function switchProduct(x)
{
    switch (x)
    {
    case 1:
        console.log('Oranges are $0.59 a pound.');
        break;
    case 2:
        console.log('Apples are $0.32 a pound.');
        break;
    case 3:
        console.log('Bananas are $0.48 a pound.');
        break;
    case 'Cherries':
        console.log('Cherries are $3.00 a pound.');
        break;
    default:
        console.log('Sorry, we are out of ');
    }
}


index.html

<button id="1" class="inline-block typeU">1</button>
greybeard
  • 2,015
  • 5
  • 20
  • 51
AndreGTH
  • 27
  • 3
  • 1
    The duplicate talks about `setTimeout`, but the problem is the same. You're *invoking* a function and then passing its *result* to `addEventListener`. Instead, pass a function itself to `addEventListener`. The simplest approach here is likely to just wrap your function call in an anonymous function as demonstrated in the first answer on the duplicate. – David May 04 '21 at 13:01
  • Thank you very much! Now i get the problem – AndreGTH May 04 '21 at 13:08

1 Answers1

1

This is because of a mistake in the event listener you add:

bttn.addEventListener("click", switchProduct(2));

This adds the result of switchProduct(2) as the event listener to the click event of the button.

Instead you need to use an anonymous function to wrap the call to switchProduct(2):

bttn.addEventListener("click", function() { switchProduct(2); });

See here in this working snippet:

let bttn = document.getElementById("1");
bttn.addEventListener("click", function() { switchProduct(2); });

function switchProduct(x){
    switch (x) {
        case 1:
            console.log('Oranges are $0.59 a pound.');
            break;
        case 2:
            console.log('Apples are $0.32 a pound.');
            break;
        case 3:
            console.log('Bananas are $0.48 a pound.');
            break;
        case 'Cherries':
            console.log('Cherries are $3.00 a pound.');
            break;
        default:
            console.log('Sorry, we are out of ');
    }
}
    <button id="1" class="inline-block typeU">1</button>
Martin
  • 14,189
  • 1
  • 26
  • 43