在动态添加的元素上填充所选国家/地区的省份

时间:2017-08-07 21:45:44

标签: javascript jquery jquery-events

动态创建联系人(添加或删除)。对于创建的每个联系人,必须选择一个国家/地区,并且必须通过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 );




1 个答案:

答案 0 :(得分: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 );

我希望它有所帮助!