Wellington Zanelli
Wellington Zanelli

Reputation: 1964

Onload jQuery event to call function and make it "live"

Exist any event in jQuery that attach an event like this:

$("body").on("click", "#test", function () {
    // some code here...
});

That I can attach to load or ready event, to replace the:

$(document).ready(function () {
    // Some code...
});

I need this because I have the $(document).ready(); scope in an external file, that do some form validation, and in my HTML I load some content by ajax, and then all is in that scope don't work.

In other words, I want that all in the $(document).ready(); stay live on the page, using something like .on.

If I put the HTML directly in the page, without ajax, the validation works.

Any idea on how I can solve this problem?

Upvotes: 0

Views: 249

Answers (2)

sudhansu63
sudhansu63

Reputation: 6190

I assume element with id "test" is appended after ajax call. then you can use like this to make the element ready.

you can add multiple document ready in a single file/ or in multiple javascript file. but i would suggest you to put your code inside a function and call that function from the document.ready scope of external file.

function doSomething()
{
    $("#test").on('click', function(){
      //do some thing here
    });
}

External file:

 $(document).ready(function(){
....
.....

try{
doSomething(); 
}
catch()
{
//this section will be hit when the method is not avavilble.
}
});

Upvotes: 0

fguillen
fguillen

Reputation: 38832

As a suggestion:

Give global access to the validation function, then use the AJAX callbacks to call this validation function.

Upvotes: 1

Related Questions