Unsuccessfully calling a function defined in JS file 2 from a function in JS file 1 AFTER the page has loaded/on-click event-Collection of common programming errors
I have two Javascript files, that I will significantly streamline to simplify the issue in hand.
form.js
function open_action_dialog(){
// code to open the dialog..
// If [Return] is pressed when focus is on the #action field, call the action confirmation function defined in the second javascript file.
$('#action').keypress(function(e){
var fn_name = "action_confirm";
if(e.which == 13)
window[fn_name]();
});
}
blog.form.js
$(function (){
$("#dialog_action_open").click(function() {
open_action_dialog();
});
function action_confirm(){
alert('action confirmed');
return;
}
});
So on my page I have a button with id dialog_action_open
when clicked opens the action dialog; this is a function from the second file successfully calling a function from the first file.
Inside the dialog, there’s an input text field with id action
where I’ve set it so that if the user presses [Return]
when their cursor is focused on the field, it should call the action_confirm()
function defined in the second file. It does pickup the keypress event, but does not call the function from the second file; inside Google’s code inspector, the error is:
Uncaught TypeError: Property ‘action_confirm’ of object [object Window] is not a function
So, my question is what do I need to do to be able to successfully call the function from the second file from inside a function in the first file? Keeping in mind, I’m aware you can’t immediately call a function defined later. But, even though my action_confirm() function is defined after the function calling it from the first file, isn’t this technicality moot considering the call is occurring AFTER the page has loaded, and more specifically AFTER a click event on the page?
I would appreciate being enlightened.
Many thanks.
-
Because the function you’re trying to call is wrapped in another function, it’s invisible to the function in your other JS.
You could remove
$(function (){
(and it’s closing});
)
Originally posted 2013-11-13 09:48:47.