0

My query is regarding using Javascript to change the value of an onclick function that already exists on the page.

There's a button. This button has the following onclick function:

onclick="if (confirm('Yahdy Yahdy yah?')) { someFunction(); }; return false;"

I would like to change the onclick function using Javascript to just be as follows and or extract the someFunction(); and run that directly without having to go through the confirmation. As I understand it, you can't confirm a confirm through scripting, so my only option is to run someFunction(); directly. My question is, how do I access someFunction() directly as someFunction() contains randomly generated values each time the page loads.

onclick="someFunction();"

That's basically what I'd like, so I can then call onclick() directly. I'm happy to use vanilla or jQuery to go about this.

TLDR: I want to extract PART of the old onclick function and make a new onclick function with JUST that part.

3
  • Another way around it I just considered was reading the current onclick value, converting that to a string, looking for the bits I need, and making a new function using those bits, and then assigning that function to the onclick. Commented Oct 31, 2013 at 23:32
  • On a related note, consider using this method for confirm: stackoverflow.com/questions/9334636/javascript-yes-no-alert/… Commented Oct 31, 2013 at 23:37
  • Not sure if that's relevant - I don't control the contents of the old onclick function, and I'm trying to modify it clientside to drop their confirm window. I can't really make a new onclick without having their dynamically generated someFunction inside. Commented Oct 31, 2013 at 23:39

1 Answer 1

2

You can do this:

var code = obj.onclick.toString();

That will give you the javascript code assigned to that click handler to which you can search through it, find what you're looking for and reassign the click handler to something else.


I have no idea if this is the best way to do it, but here's something that worked for me:

function nullConfirm() { return true;};

(function() {
    var obj = document.getElementById("test");
    var code = obj.onclick.toString();
    code = code.replace("confirm(", "nullConfirm(");
    var matches = code.match(/\{(.*)\}/);
    if (matches) {
        obj.onclick = function() {
            eval(matches[1]);
        }
    }
})();
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I thought that might be my last resort. Hey, at least I know there's no other way. Haha, thankyou.

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.