ken
ken

Reputation: 9013

Providing focus to DOM element after AJAX load

I am loading forms via AJAX ... I have what I would have thought to be a winning jQuery statement but it does nothing:

$("#input_form_container").loadActionTemplate()
                          .find ('.form-focus:first').focus();

The loadActionTemplate is a function that I've created to load the form. It does load the form and then returns a reference to "this" so that chaining can continue. The target element is an text input field that looks like this:

<input class="span1 form-focus" id="min-duration" name="min-duration" size="16" type="text">

Note:

Any help would be greatly appreciated.

Upvotes: 0

Views: 1485

Answers (1)

ken
ken

Reputation: 9013

As @Andreas points out AJAX is -- after all -- asynchronous. I had fooled myself into believing that the jQuery chain I had built somehow would fire only on the success() condition of AJAX callback. Why I thought that can only be pointed to lack of sleep, lack of access to high quality caffeine and/or amphetamines. Anyway, in attempt to share the solution, here is my "loadActionTemplate" jQuery extension:

$.fn.extend({
    // loadActionTemplate plugin
    loadActionTemplate: function(options) {
        //default settings
        var defaults = {
            actionDOM : '#do_something_dropdown',
            cache : true
        }
        // store the "this" state for safe keeping
        var domElements = $(this);
        // merge user options into default
        var options = $.extend(defaults, options);
        // assign the "action" to an easily addressible variable
        var action = $(options.actionDOM).val();
        // get the HTML form template for this action
        LG_ServiceCall ( 'get-action-template' , {'action' : action} , function( r ) {
            var res = JSON.parse ( r );
            var template = res.results.template;
            // iterate through all matched DOM instances
            return domElements.each(function() {
                // get handle on DOM object operating on
                var element = $(this);
                element.html( template );
                element.find('.form-focus:first').focus();
            })
        });
        return domElements; // allows the function to operate in a chain
    }
});

Without going into too much painful detail the LG_ServiceCall method takes three parameters:

function LG_ServiceCall( $service , $options , $callback );

The callback function passed into the third parameter is called when the AJAX.success() method is called:

requestObj.success = function (r) {
    console.log ("Successful AJAX Call ( " + JSON.stringify (r) + ")");
    callback (r);
}

Upvotes: 1

Related Questions