2017-08-07 18 views
0

連絡先は動的に(追加または削除されて)作成されます。作成された連絡先ごとに、国を選択し、その国の州をajax経由でロードする必要があります。動的に追加された要素上の選択された国に州を設定します。

Parent element 
#contacts 

Child elements 
#contacts_0_country 
#contacts_0_provinces 

#contacts_1_country 
#contacts_1_provinces 
etc 

すべては私が担当するAJAX用の二回国の選択を切り替え、国の地方を変更する必要があることを除いて完璧に動作は、この問題は、以下にjsの原因である

を選択したが、私はそれを見つけるカント:

(function ($) { 
 
    'use strict'; 
 

 
     $(document).ready(function() { 
 
    
 
    $('#contacts').on("change", [$('select')],function() { 
 
    $("select[id^='contacts'][id$='_country']").each(function() { 
 
    var id = parseInt(this.id.match(/\d+/), 10); 
 
    var $country = $("#contacts_" + id + "_country"); 
 
    var $province = $("#contacts_" + id + "_provinces"); 
 
    
 
    // When country gets selected ... 
 
    $country.on('change',["#contacts_" + id + "_country"], function() { 
 
     // ... retrieve the corresponding form 
 
     var $form = $(this).closest('form'); 
 
     // Simulate form data, but only include the selected value 
 
     var data = {}; 
 
     data[$country.attr('name')] = $country.val(); 
 
     
 
     // Submit data via AJAX to the form's action path 
 
     $.ajax({ 
 
      url : $form.attr('action'), 
 
      type: $form.attr('method'), 
 
      data : data, 
 
      success: function(html) { 
 
      // Replace current province field ... 
 
      $("#contacts_" + id + "_provinces").replaceWith(
 
      // ... with the returned one from the AJAX response 
 
      $(html).find("#contacts_" + id + "_provinces") 
 
      ); 
 
      // Province field now displays the appropriate provinces 
 
      } 
 
     }); 
 
    }); 
 
    }); 
 
    }); 
 
    }); 
 
})(jQuery);

答えて

0

私は自分の質問への答えを見つけました。以下は現在完全に動作しています。州は、選択した当該国のために移入され、これはまた、コレクション

(function ($) { 
 
    'use strict'; 
 

 
    
 
    $(window).load(function() { 
 
      
 
    $('#contacts').on("click", [$('select')], function(event) { 
 
    var $id = event.target.id; 
 
    var id = parseInt($id.match(/\d+/), 10); 
 
    var $country = ('#' + $id); 
 
    var $country = $($country); 
 
    
 
     var $form = $country.closest('form'); 
 
      // Simulate form data, but only include the selected value 
 
     var data = {}; 
 
     data[$country.attr('name')] = $country.val(); 
 
     
 
     // Submit data via AJAX to the form's action path 
 
     $.ajax({ 
 
      url : $form.attr('action'), 
 
      type: $form.attr('method'), 
 
      data : data, 
 
      success: function(html) { 
 
      // Replace current province field ... 
 
      $("#contacts" + id + "_provinces").replaceWith(
 
      // ... with the returned one from the AJAX response 
 
      $(html).find("#contacts" + id + "_provinces") 
 
      ); 
 
      // Province field now displays the appropriate provinces 
 
      } 
 
     }); 
 
    //}); 
 

 
    }); 
 
    }); 
 
})(jQuery);

に動的に追加された新しい連絡先に動作します私はそれが誰かを役に立てば幸い!

関連する問題