views:

23

answers:

2

All of the tutorials I see online are defining functions on the fly to respond to event handlers. I am trying to call a JS function when my form is submitted, but it never works quite right. In PHP:

echo "$(document).ready(function() { $(\"#newDate\").submit( ValidateForm('".$ID."') ); });";

When the user hits enter for the input field, instead of submitting my form I need it to call a javascript function. This line of code repeatedly calls my function in an infinite loop.

+2  A: 

You need an anonymous function to wrap it, like this:

echo "$(document).ready(function() { $('#newDate').submit(function() { ValidateForm('".$ID."'); }); });";

I changed to single quotes on #newDate as well just because it's a bit cleaner to me, if it doesn't work for you just leave the \" style...it's not related to the actual problem.

Without the anonymous function it's trying to validate the field immediately and assign the result to the event handler, which isn't what you're after.

Nick Craver
A: 

Close. It should look like this:

echo "$(function() {\n\t",
     "$('#newDate').submit(function() {\n\t\t",
     "ValidateForm('" . $ID . "');\n\t",
     "});\n});";

I added some formatting to make things look more readable once you examine source.

Notice the new anonymous function. That will get things working right for you.

Stephen