Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
135
rated 0 times [  140] [ 5]  / answers: 1 / hits: 22870  / 8 Years ago, sat, july 2, 2016, 12:00:00

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.


More From » jquery

 Answers
28

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>




[#61544] Wednesday, June 29, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
destiney

Total Points: 175
Total Questions: 96
Total Answers: 93

Location: Zambia
Member since Sat, Nov 6, 2021
3 Years ago
;