tags:

views:

51

answers:

2

Hi all,

I have the following Jquery script:

$(document).ready(function() {
// When the submit button of the new team form is clicked...
$('#new_team').submit(function() {
  // Disable & rename the save button
  $('input#save_button', this).attr('disabled', 'disabled').val('Saving...');
  // Fade in the saving message
  $("#saving-msg").fadeIn(200);
});

// Perform the AJAX request to the server
$('#new_team').ajaxForm({
  url: "/teams/create.json",
  type: "POST",
  dataType: "json",
  beforeSubmit:  function(formData, jqForm, options) {},
  success: function(response) {
    if(response.success == true) {
      // If no errors then redirect
      window.location = "/teams/" + response.team_id;
    } else {
      // Enable and rename the save button
      $('input#save_button').removeAttr('disabled').val('Save');
      // Output errors
      $("#error_messages").html(errorMessages(response)).hide().fadeIn(300);
      // Fade out save message
      $("#saving-msg").fadeOut(200);
      // Scroll to the top
      window.scrollTo(0,0);
    }
  }
}); });

Is there anyway to simplify this script and also make it reusable for different forms?

  • There is only ever one form on a page
  • The buttons are always labelled the same
  • Each form has a unique ID

Thanks!

A: 

You reference the form's id twice; you could instead abstract the function you pass to $(document).ready away into a function which takes an argument (the id of the form) and then just pass in a different name each time using a closure.

function abstracted_ajax_form($formid)
{
    ...
}

$(document).ready(function() { abstracted_ajax_form('#new_team'); });
Amber
A: 

Just a couple of thougths. Instead of using the ID, you can create a class for the form and have the id of the save button and msg look like this:

<id_of_form>_save_button
<id_of_form>_error_msgs
<id_of_form>_saving_msg


$(document).ready(function() {
    $('.ajax_form').submit(function() {
        $('.save_button', this).attr('disabled', 'disabled').val('Saving...');
        $(this.attr('id')+"_saving_msg").fadeIn(200);
    }
);

You can use the same idea for the AJAX request.

jobscry
I think it would be easier to use $(this).find, to look for the buttons within the context of the form.
good call, jquery rocks!
jobscry