Reputation: 79
I've build an express app and its working perfectly, in the final stage I want to add some alert messages to pop when some button are clicked. But my alerts are poping without even clicking, the moment page containing the button is loaded pop up shows
In my index.js
file I have a form button for deleting
<form
action="/grades/<%=grade._id%>?_method=DELETE"
method="POST"
class="delete-form"
>
<input
type="submit"
class="btn btn-danger mt-3"
value="Delete Class"
id="delBtn"
>
</form>
I've given ID delBtn
for the button,
and inside my main.js
I have
var delBtn = document.querySelector('#delBtn');
delBtn.addEventListener('click', alert('Button Clicked'));
How can I get this to work properly..
Upvotes: 0
Views: 710
Reputation: 5704
This line is the problem. You call alert
immediatelly.
delBtn.addEventListener('click', alert('Button Clicked'));
it will behave just like this
alert('Button Clicked');
delBtn.addEventListener('click', undefined);
The addEventListener
function expects a string and a function but you are not passing in a function but undefined
since that is what alert
function returns.
So all you need is this
delBtn.addEventListener('click', function(){
alert('Button Clicked');
});
Upvotes: 2
Reputation: 482
I think you missed callback function in event listener
delBtn.addEventListener('click', function(){alert('Button Clicked')});
Upvotes: 1