0

How should I make this button Work?

I added this javascript line just to check but it also shows an alert without even clicking on the buttons.

document.querySelector(".btnminus").addEventListener(onclick,alert("hello"));
<div class="quantity d-inline-block">
<input class="btn btnminus d-inline" type="button" value="-" >
 <input type="number" class="form-control d-inline itemnumber" value="0" aria-label="Username" aria-describedby="addon-wrapping">
<input class="btn btnminus d-inline" type="button" value="+" >
kuchnahi
  • 51
  • 6
  • You've included a version 3 Bootstrap script, which would require jQuery and has different syntax. Please update the snippet demo to use library versions that match your tags. – isherwood Dec 31 '21 at 18:44

1 Answers1

2

Two things:

First, what is onclick? The first argument to addEventListener is the name of the event as a string, which in this case should be 'click'. I suspect the only reason this isn't throwing an error is because onclick exists at the window level and, like anything, can be interpreted as a string. But it's not the string you want. The string you want is simply 'click'.

Second, you're running the alert immediately and setting its result as the click handler. And it doesn't return anything so that result is undefined. Use a function for the event handler, not the result of a function. (Unless the result of that function is itself a function meant to be an event handler, of course.)

Putting them together:

document.querySelector(".btnminus").addEventListener('click', function () {
  alert("hello");
});
David
  • 208,112
  • 36
  • 198
  • 279
  • how should I make it work that when buttons have clicked the value inside changes accordingly? also, the alert is only working on the first button but not on the second why is it so? – kuchnahi Dec 31 '21 at 18:48
  • 1
    @kuchnahi: (1) By writting logic inside that `function` to modify the value of the `` element. There are tutorials and examples online to help you learn more JavaScript and how to do things like that. (2) Because you're only adding an event handler to the first element matching that selector, since `querySelector` only returns one element. [There are other methods for finding elements.](https://stackoverflow.com/q/10693845/328193) – David Dec 31 '21 at 18:51