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/
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 thekeyupof each of your inputs, instead of callingcalcme()directly. See the fiddle below.Working fiddle: http://jsfiddle.net/vpsSA/1/
In your
ready()handler, the bind statement comes after thecaclme()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 thecalcme()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 fromcalcme()when running on load. Are you using anything insidecalcme()thats initialized after running it on load. I would suggest putting in adebugger;statement as the first line in yourready()handler and tracing it in Firebug or Chrome.