Search code examples
jqueryajaxform

how to use $(this) in jquery ajaxform plugin


i have 3 forms in similar fieldsets using ajaxform. What i want is when a form is updated, it should only update its parent fieldset. what happens right now is because i don't have a $(this) variable i can't specify ajaxform that i only want to update the submitted form:

$(".toggle-form-submit").parents("form").ajaxForm({
  dataType: 'html',
  success: function(html) {
    var myForm = $(this);
    console.log(myForm);
    if(myForm.parents("fieldset").find(".replaceable").length) {
      updateReplaceableAndClearAndCloseFormWithin(myForm.parents("fieldset"), html);
    } else {
      longPanelUpdateReplaceableAndClearAndCloseFormWithin(myForm.parents("fieldset"), html);
    }
    if( $(".test-categories-list").length) {
      initSortableTestCases();
    }
  }
});

Apparently myForm is the response object. what i want is the jquery selector for the current form so that it can find it's parents. I can't set a variable in the ajaxform instantiation so where should i set $(this)/myForm?


Solution

  • Assuming you are using this jQuery Ajax form plugin, the 4th argument of the success method will be the jQuery wrapped form that was acted on:

    http://jquery.malsup.com/form/#options-object

    So this should work:

    $(".toggle-form-submit").parents("form").ajaxForm({
      dataType: 'html',
      success: function(html, status, xhr, myForm) {    
      console.log(myForm);
      if(myForm.parents("fieldset").find(".replaceable").length) {
        updateReplaceableAndClearAndCloseFormWithin(myForm.parents("fieldset"), html);
      } else {
        longPanelUpdateReplaceableAndClearAndCloseFormWithin(myForm.parents("fieldset"),     html);
      }
      if( $(".test-categories-list").length) {
        initSortableTestCases();
      }
     }
    });