2009-08-13 10 views
0

私は、次のjQueryのスクリプトを持っている:このJqueryスクリプトを簡略化できますか?

$(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); 
    } 
    } 
}); }); 

は、このスクリプトを簡素化し、また、それがさまざまな形態のために再利用可能にするとにかくはありますか?

  • ボタンは常に同じ
  • 各フォームにラベル付けされているページにのみ、これまで一つの形態があるが、固有IDに

感謝しています!

+0

これは本当に良い方法ではありませんが、フォームが1つしかないので、セレクタ$( 'form')を使用してフォームを参照できます。次に、$(this).find( 'input#save_button')を使用できるように、そのフォームの子としてボタンを参照します。 – user120242

答えて

0

ほんの数分です。代わりにIDを使用して、あなたは、フォームのクラスを作成し、保存ボタンのIDを持っているとMSGは次のようになります。

<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); 
    } 
); 

あなたはAJAX要求に同じアイデアを使用することができます。

+1

$(this).findを使用して、フォームのコンテキスト内でボタンを探す方が簡単だと思います。 – user120242

+0

良い呼び出し、jqueryの岩! – imjoevasquez

0

フォームのIDを2回参照します。代わりに$(document).readyに渡す関数を引数(フォームのid)をとり、クロージャを使うたびに別の名前を渡す関数に抽象化することができます。

function abstracted_ajax_form($formid) 
{ 
    ... 
} 

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