Why am I unable to initializing a jQuery function within a getScript callback?

829 views Asked by At

My specific question/problem has to do with implementing v1.7 of Cedric Dugas' jQuery validation plugin (http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/#comments), BUT I believe the issue can easily be generalized to other situations.

Typically I load the following script like so:

<script src="inc/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script> 

Then to initialize the plugin, I do the following:

<script> 
$(document).ready(function() {      
    $("#myFormID").validationEngine();
});
</script>

I have a form with an id attribute with a value of "myFormID" and the script validates the form fields. This works.

However, if I include the two bits of code on every page, but the page does not have a form with an ID of myFormID, then I get a null error. To try to address this problem and make the plugin load only when an appropriate form exists, I tried this:

<script>
    if($('#myFormID').length) 
    {
        $.getScript('inc/formValidator/js/jquery.validationEngine.js', function() {
            alert('Load was performed.');
        });
    };
</script>

That works fine too. However, now I can't figure out how to initialize the validationEngine and bind it to the form. Why doesn't this work?

    $.getScript('inc/formValidator/js/jquery.validationEngine.js', function() 
    {
        $("#myFormID").validationEngine();
    });

I also tried this:

    $.getScript('inc/formValidator/js/jquery.validationEngine.js', function() 
    {
        $("#myFormID").load(function()
        {
            $(this).validationEngine();
        });
    });

No luck. I get this error: $("#myFormID") is null.

Ideas? I'm nearly bald as it is. This isn't helping!

2

There are 2 answers

0
technoTarek On BEST ANSWER

Turns out it was a Prototype conflict from a script added by another developer. There was nothing inherently wrong with

<script>
    if($('#myFormID').length) 
    {
        $.getScript('inc/formValidator/js/jquery.validationEngine.js', function() {
            $("#myFormID").validationEngine();
        });
    };
</script>
1
Tania Petsouka On

You can include the js in all of your pages, but call validationEngine only when form exists. Like that:

<script src="inc/formValidator/js/jquery.validationEngine.js" type="text/javascript"></script> 

  
$(document).ready(function() {
if($('#myFormID').length) 
    {
     $("#myFormID").validationEngine();
    }
});