Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent onclick from firing

I was working around with form submissions in html. Please take a look at below code

<form id="form1">
 <button id="btn1" onclick="clicked();">Submit</button>
</form>
<script>
    $("#btn1").click(function (event) {
        alert("event triggered");
        if(some_condition == true){
             // stop firing onclick method but it always submits the form
             event.stopImmediatePropogation(); // not working
             event.preventDefault(); // not working
             event.stopPropogation(); // not working it's for bubbled events
         }
     });
     function clicked(){ alert("clicked me"); }
</script>

I want to stop clicked() function from firing which is attached to inline onclick attribute. I would like to run my jquery click function and if something goes wrong, I dont want to trigger onclick but it always runs clicked() function. Could any one help me. Any help is greatly appreciated.

like image 236
user3205479 Avatar asked Oct 26 '25 14:10

user3205479


1 Answers

The order in which an onxyz handler is called relative to dynamically-attached handlers varies from browser to browser, so your handler may well not run before the original does.

To deal with that, you save and remove the onclick handler:

var btn = $("#btn1");
var clickHandler = btn[0].onclick;
btn[0].onclick = false;

Then, in your handler, if you want that function to be called, you call it:

clickhandler.call(this, event);

Example:

// Get the button
var btn = $("#btn1");

// Save and remove the onclick handler
var clickHandler = btn[0].onclick;
btn[0].onclick = false;

// Hook up your handler
$("#btn1").click(function(event) {
  alert("event triggered");
  if (!confirm("Allow it?")) {
    // Disallowed, don't call it
    alert("stopped it");
  } else {
    // Allowed, call it
    clickHandler.call(this, event);
  }
});

// The onclick handler
function clicked() {
  alert("clicked me");
}
<form id="form1" onsubmit="return false">
  <button id="btn1" onclick="clicked();">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 123
T.J. Crowder Avatar answered Oct 29 '25 02:10

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!