Search code examples
jqueryjquery-selectorsajaxform

select tag using $(this), from ajaxform plugin constructor


Note : I have titled it very poorly, please help me improve it, if you understand my question

I am using ajaxform submit for all of my forms. I am able to programatically add a feedback div to each form successfully. I want to select only current form in my page. I am using following code.

 $('form').append('<div class="feedback" />');
    $('form').ajaxForm
    ({      
        success: function(responseText)
        {
            if(responseText=="1")
            {           
                $(this).clearForm();
                $(this).children('INPUT,select').eq(0).focus();
            }
            else    
            {
                alert($(this).children().length); // This gives me 0
                $(this).children('.feedback').eq(0).html(responseText); 
            }
        }
    });

I can do the above successfully only if I have one form in whole page using $('form') instead of $(this) but it makes problem when i have multiple forms in a page


Solution

  • If you look closer at the docs, will see that the success callback is passed 4 arguments

    1.) responseText or responseXML value (depending on the value of the dataType option).
    2.) statusText
    3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
    4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
    

    Use the last argument instead of $(this) for current form instance

    See options tab of docs

    Update by asker : working code from above answer I got is following

    Instead of $(this) I could do following

    $('form').append('<div class="feedback" />');
    var options = { success: showResponse  };
    $('form').ajaxForm(options);
    function showResponse(responseText, statusText, xhr, $form)
    {
        if(statusText == 'success')     
            $form.children('.feedback').html(responseText);
    }
    

    Link of example followed