Search code examples
javascriptjquerypreventdefault

prevent default is not working in function


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


Solution

    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.