1

Change onclick function using javascript ?

for example

normally checkbox is onclick="fn()"

after alert(TEST); i want to change from onclick="fn()" to onclick="return false;"

How can i do that ?

http://jsfiddle.net/8xhc5p4n/2/

$(window).load(function(){
    $("#check_box").change(function fn() {        
        alert("TEST");
        // change from `onclick="fn()"` to `onclick="return false;"`
    });
});
1
  • 2
    SOunds like api.jquery.com/one is what you should be using and not using an inline event? Commented Nov 13, 2015 at 14:59

8 Answers 8

3

Better way:

var check = true;
function fn(){
   if(check)
     {
        alert(...);
        check = false;
     }
   else return false;
}
Sign up to request clarification or add additional context in comments.

Comments

2
    $(window).load(function(){
        $("#check_box").change(function fn() {        
            alert("TEST");
            $("#check_box").attr("onclick","return false;");
            //change from `onclick="fn()"` to `onclick="return false;"`
        });
    });

Comments

1
$(window).load(function(){
    $("#check_box").change(function fn() {        
        alert("TEST");
        //change from `onclick="fn()"` to `onclick="return false;"`
        this.setAttribute("onclick","return false;");
    });
});

Comments

1

It can be solved in two ways, if you are using jQuery

$('#check_box').on('click', function(){
    $(this).attr('onclick', 'return false;');
})

or if you want to use vanilla / EcmaScript 5

document.querySelector("#check_box").addEventListener('click', (function(){
    this.setAttribute('onclick', 'return false;');
})();)

Comments

0

You can use jQuerys on a off functions

http://jsfiddle.net/8tq300mk/

Comments

0

I believe you have already answered your own question.

<input type="checkbox" id="check_box" name="check_box" value="Shared" onclick="return false">

is completely valid code.

Comments

0

You can use $(this).attr('onclick', 'return false;'); as shown below:

$(window).load(function(){
    $("#check_box").change(function() {        
        $(this).attr('onclick', 'return false;');
    });
});

Here's an updated version of your JSFiddle.

Comments

0
$(window).load(function(){
    $("#check_box").change(function fn() {        
        alert("TEST");

        $("#check_box").click(function() {
            return false;
        });
    });
});

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.