Vytalyi
Vytalyi

Reputation: 1695

Prevent onclick execution with jquery

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

Answers (4)

Gurpreet Singh
Gurpreet Singh

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 );
})​

DEMO

Upvotes: 1

T.J. Crowder
T.J. Crowder

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

Esailija
Esailija

Reputation: 140234

$(document).ready(function() {
    $("#btn").click(function() {
        alert("Want to show only this message");        
        return false;
    }).prop("onclick", null );
})​

http://jsfiddle.net/B5GWx/5/

Upvotes: 7

ilivewithian
ilivewithian

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

Related Questions