1

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 ?

FIDDLE HERE

Tushar
  • 85,780
  • 21
  • 159
  • 179
Nitish
  • 2,695
  • 9
  • 53
  • 88

2 Answers2

3
  1. Use 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.
  2. Use 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.
  3. It is better practice not to use inline events. Use addEventListener to bind events on an element from Javascript.
  4. If you have jQuery loaded on the page, you can use jQuery's on method to bind events.
  5. Use 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').

Updated Fiddle

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.

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • To know more about jsfiddle options see bottom part of http://stackoverflow.com/a/32925927/2025923 – Tushar Oct 10 '15 at 10:11
2

You can use the addEventListener() to bind your function on particular event. Something like

document.getElementById('makePaid').addEventListener('click', function(event) {
  makePaidModalView(this.dataset.id, event);
});

function makePaidModalView(id, e) {
  e.preventDefault();
  alert(id);
}
<a href="#" id="makePaid" data-id=1>Make Paid</a>
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
  • 1
    The parameter `1` here is hardcoded/static, to make it more dynamic/flexible use `data-*` attribute to store id on element, check the second code snippet in my example for the reference of how to use `data-*` attribute – Tushar Oct 10 '15 at 10:15
  • Yeah we can do this, Updated the answer now. – Suman Bogati Oct 10 '15 at 10:16