What's the best way to avoid duplicating code in these two functions that do the same thing?

Given this form (which contains a submit button):

<form id="review_form">
  <input type="submit" id="btn_submit" value="Submit with ajax! (submit button)">
</form>

      

and this link (to submit the same form):

<a href="#" id="lnk_submit">Submit with ajax! (hyperlink)</a>

      

In the following jQuery code, when the element is clicked #btn_submit

, the form (is #review_form)

submitted with ajax:

jQuery.fn.submitWithAjax = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

$(document).ready(function() {
  $("#btn_submit").submitWithAjax();
})

      

What I want to do is remove the submit button and submit the form using the link above ( #lnk_submit

) something like this:

$("#lnk_submit").click(function(){ 
   $("#review_form").submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
    }); 
   return false;
});

      

But the problem is that this duplicates all the code in the jQuery.fn.submitWithAjax

one defined above.

What's the best way to avoid code duplication here?

+2


source to share


4 answers


How about you have a function like this:

function submitWithAjax() {
    $("#review_form").submit(function() {
        $.post(this.action, $(this).serialize(), null, "script");
        return false;
    });         
}

      



And then bind both actions to a function:

$(document).ready(submitWithAjax);
$("#lnk_submit").click(submitWithAjax);

      

+2


source


I might be oversimplifying, but can't you just assign the function to a variable and reuse it?



var submitWithAjaxFn = function() {
  this.submit(function() {
    $.post(this.action, $(this).serialize(), null, "script");
    return false;
  })
  return this;
};

jQuery.fn.submitWithAjax = submitWithAjaxFn;
$("#lnk_submit").click(function(){ 
   $("#review_form").submit(submitWithAjaxFn); 
   return false;
});

      

+1


source


The simplest answer (albeit maybe not the most elegant one) is to use a second function for both (which explicitly references your form no matter what calls the function), and then give each trigger the same class and attach a click event for both ...

0


source


If you want the same functionality from a hyperlink, make the hyperlink action a simple click of a button.

$('#lnk_submit').click(function(e){ $('#btn_submit').click(); return false; });

      

0


source







All Articles