How to prevent default in an onclick method? I have a method in which I am also passing a custom value
<a href="#" onclick="callmymethod(24)">Call</a>
function callmymethod(myVal){ //doing custom things with myVal //here I want to prevent default }
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
We can prevent this default behaviour by making a small modification to the definition of the handleSubmit function. We call a preventDefault on the event when submitting the form, and this will cancel the default event behavior (browser refresh) while allowing us to execute any code we write inside handleSubmit.
The event. preventDefault() method stops the default action of an element from happening.
A click on a form submit button – initiates its submission to the server. Pressing a mouse button over a text and moving it – selects the text.
Let your callback return false
and pass that on to the onclick
handler:
<a href="#" onclick="return callmymethod(24)">Call</a> function callmymethod(myVal){ //doing custom things with myVal //here I want to prevent default return false; }
To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).
The mark-up:
<a href="#" id="myAnchor">Call</a>
The code (separate file):
// Code example using Prototype JS API $('myAnchor').observe('click', function(event) { Event.stop(event); // suppress default click behavior, cancel the event /* your onclick code goes here */ });
In my opinion the answer is wrong! He asked for event.preventDefault();
when you simply return false; it calls event.preventDefault();
AND event.stopPropagation();
as well!
You can solve it by this:
<a href="#" onclick="callmymethod(event, 24)">Call</a>
function callmymethod(e, myVal){ //doing custom things with myVal //here I want to prevent default e = e || window.event; e.preventDefault(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With