0

I picked up a project that another developer built. He has some of the JavaScript on the actual php page which is making debugging difficult.

<button type="submit" onclick="doFunction(event)">Done</button>

I have tried to move it to a javascript file:

$( document ).ready(function() {
    function doFunction(e){}
}); 

and removing it from the PHP page but now it's not firing. Why is it not working now and how do I fix it?

5
  • did you load the external file? <script src="yourcode.js"></script>? the browser isn't going to magically realize that you moved the code elsewhere. Commented Dec 7, 2015 at 16:28
  • Yes, I put it in a .js file being used already. Commented Dec 7, 2015 at 16:28
  • e is undefined within your .ready(). I suggest you look at your js console for errors. Commented Dec 7, 2015 at 16:29
  • Is it after the jquery library include? Commented Dec 7, 2015 at 16:29
  • Did you leave the <button type="submit" onclick="doFunction(event)">Done</button> or is that the previous solution that you've removed? Commented Dec 7, 2015 at 16:30

1 Answer 1

4

You've defined function doFunction(e){} inside another function.

That locally scopes it. It is not a global. It is not accessible from onclick attributes (since they aren't defined inside the same function).

Don't use onclick attributes, they have many problems, bind your event handlers with JavaScript instead.

Since you are using jQuery:

$('button').on('click', doFunction);

You can use a more specific selector if you like.

That said, almost anything you want to do with a submit button is clicked is better done when a form is submitted.

$('form').on('submit', doFunction);
Sign up to request clarification or add additional context in comments.

5 Comments

How can I make it globally accessible?
Don't. Globals are evil.
@DavidTunnell define function doFunction(e) in the global scope and not inside the $( document ).ready function call. If you don't want to pollute the global scope, you can define an object in the global scope with doFunction as one of it's properties.
As a trick, you can do : window['doFunction'] = function(e){} But this is bad practice
@DavidTunnell, While I agree with the sentiment of Quentin on not making it global, some projects in the real world don't have the budgets to do things the right way. this project may have hundreds of these calls baked into the HTML. And yes, I'd use Robin's method or window.doFunction = function(e){ ... };

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.