Reputation: 739
I apologize for this rather BASIC question, but I am at whits end here!
I have a javascript function that I want to run when the page loads... simple right? I have tried putting the function in doc readys, window readys, putting it before and after the main function, etc etc. NOTHING seems to work.
Code so far:
function calcme() {
DA FUNCTON
}
$(document).ready(function(){
calcme();
$("input").bind("keyup", calcme);
});
Please note... the keyup bind DOES work, but I need the calcme function to load on page load. Thoughts?
UPDATE: As per request, here is the full fiddle. http://jsfiddle.net/vpsSA/
Upvotes: 0
Views: 233
Reputation: 66663
Problem found: The calcme()
function assumes it is called from the context of one of the inputs and uses this.value inside. So, when you call it without any arguments, it obviously fails. This can be solved by trigger the keyup
of each of your inputs, instead of calling calcme()
directly. See the fiddle below.
Working fiddle: http://jsfiddle.net/vpsSA/1/
In your ready()
handler, the bind statement comes after the caclme()
call. And as you mentioned the event binding worked. This means:
a) calcme()
was definitely executed on load. There is no other way since you've mentioned that the binding statement which comes after the calcme()
call worked as expected.
b) calcme()
did not throw any JS errors - if so, it would have stopped at the error and the event binding would not have taken place. Maybe it threw a warning, which you'll be able to see in your JS console.
c) Since you haven't provided whats inside calcme()
, we can't say for sure. But what it looks like is some sort of condition failure because of which you did not get the expected result from calcme()
when running on load. Are you using anything inside calcme()
thats initialized after running it on load. I would suggest putting in a debugger;
statement as the first line in your ready()
handler and tracing it in Firebug or Chrome.
Upvotes: 1
Reputation: 14967
try this:
function calcme() {
try {
//your code
}
catch(e) {
alert('error: ' + e);
}
}
if (typeof $ === undefined)) {
alert('not jquery');
}
$(document).ready(function(){
if (typeof calcme === undefined) {
alert('calcme not exist');
}
else {
calcme();
$("input").bind("keyup", calcme);
}
});
Upvotes: 0