Reputation: 51
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="+" >
Upvotes: 0
Views: 740
Reputation: 219117
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");
});
Upvotes: 2