I am trying to add preventDefault()
for a function as below :
HTML:
<a href="#" id="makePaid" onclick="makePaidModalView(1, evnt)">Make Paid</a>
Javascript:
function makePaidModalView(id, e) {
e.preventDefault();
alert(id);
}
But it is not alerting anything. Console says ReferenceError: e is not defined
. How do I add the preventDefault()
in this function ?
No wrap
option from Jsfiddle Left panel, by selecting this option will make the function makePaidModalView
global, otherwise it'll be wrapped inside load
or DOMContentLoded
callback and cannot be accessed from HTML.event
as the name of the event parameter from the event handler. As evnt
is not defined, undefined
will be passed to the function and error will be thrown when trying to access method on undefined.
addEventListener
to bind events on an element from Javascript.on
method to bind events.data-*
custom attributes to store the data related to an element on the element itself. You can access this from JS by using data('dataName')
.function makePaidModalView(id, e) {
e.preventDefault();
//console.log(id)
alert(id);
}
<a href="#" id="makePaid" onclick="makePaidModalView(1, event)">Make Paid</a>
Using jQuery on
with data-*
custom attribute to store data on element.
$(document).ready(function() {
$('#makePaid').on('click', function(e) {
alert($(this).data('id'));
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<a href="#" id="makePaid" data-id="1">Make Paid</a>
Sidenote: You can also use return false;
from the event handler when using jQuery to prevent default action of the element and also stop the event from bubbling up the DOM.