Reputation: 1695
UPDATED
Html Code:
<input type="textbox" id="textbox" value="">
<input type="button" id="btn" value="Validate" onclick="document.write('VALIDATION PASSED')" />
JS Code:
$(document).ready(function() {
$("#btn").click(function() {
if ($("#textbox").val().length == 0) {
alert("Validation error");
return false;
}
}).prop("onclick", null );
})
I have updated my code. So the issue is that after first click my onclick event stopped working. How I could fix it?
P.S. Please DO NOT change html code. I have some reasons to ask about it, but please could you please do it only with javascript? I realize that probably this is not the most easy way but I have some technical limitations in my application.
Thanks!
JSFiddle http://jsfiddle.net/B5GWx/12/
Upvotes: 2
Views: 1943
Reputation: 21233
Just removing the DOM handler will do the job. No need to return false;
or e.preventDefault();
$(document).ready(function() {
$("#btn").click(function(e) {
alert("Want to show only this message");
}).prop("onclick", null );
})
Upvotes: 1
Reputation: 1075855
You can't reliably, cross-browser, use a DOM2 handler to prevent a DOM0 handler from running.
What you can do, though, is remove the DOM0 handler entirely:
$(document).ready(function() {
var btn = $("#btn");
btn.click(function() {
alert("Want to show only this message");
return false;
});
btn[0].onclick = null; // <==== Here
});
Upvotes: 2
Reputation: 140234
$(document).ready(function() {
$("#btn").click(function() {
alert("Want to show only this message");
return false;
}).prop("onclick", null );
})
Upvotes: 7
Reputation: 19712
You are looking for preventDefault
Description: If this method is called, the default action of the event will not be triggered.
$(document).ready(function() {
$("#btn").click(function(e) {
alert("Want to show only this message");
e.preventDefault();
})
})
Upvotes: -3