Search code examples
javascriptdom-events

How to solve deprecated "event.PreventDefault()"?


I have until now with success used event.preventDefault() in the following situation where I click on a button and creates a dialogbox in Javascript:

This part creates a button in Javascript:

var vGetBtn = document.createElement("input");
vGetBtn.type = "image";
vGetBtn.id = "btnGet";
vGetBtn.src = "/someimage.png";
vGetBtn.onclick = function (event) {
    myMethod(BodyControlName, AVoucherNo);
}

And this part is the function which has been called from the button

function myMethod(ABodyControlName, AVoucherNo) {
    event.preventDefault();
    voucherNo = AVoucherNo;
    // Create a dialogbox in JavaScript
}

But now event is deprecated - so what can I do instead with Javascript? Is there maybe something I can do in JQuery instead?

I have googlet a lot without finding the correct answer ...

Regards, Michael

UPDATE

This is what I have tried now - but the code does not reach the alert()... ? So maybe this is the real problem? Now the error is the following: "Uncaught TypeError: AEvent.preventDefault is not a function"

vGetBtn.onclick = function (event) {
    myMethod(event, BodyControlName, AVoucherNo);
}
function myMethod(AEvent, ABodyControlName, AVoucherNo) {
    AEvent.preventDefault();
    alert('hello');
}

Solution

  • As noted, you should pass the event object to the handler function:

    var vGetBtn = document.createElement("input");
    vGetBtn.type = "button";
    vGetBtn.id = "btnGet";
    vGetBtn.value = 'Click me';
    vGetBtn.onclick = function (event) {
        myMethod(event, 'foo', 'bar');
    }
    
    document.body.appendChild(vGetBtn);
    
    function myMethod(event, ABodyControlName, AVoucherNo) {
        console.log(event);
        event.preventDefault();
        voucherNo = AVoucherNo;
        // Create a dialogbox in JavaScript
    }
    

    https://jsfiddle.net/thebluenile/8yarqmx2/

    This works fine, so there must be something in your code that causes the error?