0

I want to run a jquery function on html loaded through ajax. How can I do it. Please see that I cant use it inside $.ajax() because this ajax() function is already managed by another module in the system and I cant hook into it. I tried the following, but its not changing the value of input field loaded via ajax. Any idea?

$(document).on("ready", function(){
    run_my_function();
});
function run_my_function(){
    $('selector_on_html_loaded_through_ajax').val('Hi');
}   
user632347
  • 835
  • 2
  • 9
  • 21
  • You can't set a value on something that does not exist, no matter what method you try to use. You'll have to wait until the element exists before you can set it's value. – adeneo Dec 25 '12 at 13:27
  • @adeneo then it would be worthwhile to be notified when the element comes into existence. – John Dvorak Dec 25 '12 at 13:29

1 Answers1

1

There is a pseudo-event in jquery that will allow you to run code when any, jquery initiated, ajax request is successful. There maybe more efficient methods, like in the ajax success handler of the request you're making.

$.ajaxSuccess(function () {
    $('selector_on_html_loaded_through_ajax').val('Hi');
});

/// or ///

$.ajax({
    'url': 'http://example.com/this/is/my/request',
    'success': function () {
        $('selector_on_html_loaded_through_ajax').val('Hi');
    }
});

Update: Another option

Another option would be to use DOM mutation events. The only problem is that they are deprecated. This question describes how to use them cross platform.

Community
  • 1
  • 1
AaronAsAChimp
  • 530
  • 7
  • 18