不工作在jquery中选择选项动态字段

时间:2014-10-10 18:28:43

标签: javascript jquery select

    jQuery(function() {
      var currentCount = 0;
      jQuery('#addMoreEmail').click(function() {
        currentCount = cloning('#MoreEmailDetails', '#MoreEmails', currentCount);
        return false;
      });

      function cloning(from, to, counter) {
        var clone = $(from).clone();
        //console.log(clone);
        counter++;

        // Replace the input attributes:
        clone.find(':input').each(function() {
          var name = jQuery(this).attr('name').replace(0, counter);
          var id = jQuery(this).attr('id').replace(0, counter);
          jQuery(this).attr({
            'name': name,
            'id': id
          }).val();
        });


        // Replace the label for attribute:
        clone.find('label').each(function() {
          var newFor = jQuery(this).attr('for').replace(0, counter);
          jQuery(this).attr('for', newFor);
        });

        // Replace the text between html tags:
        clone = clone.html().replace(1, counter);
        jQuery(to).before(clone);

        return counter;
      }

    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="MoreEmailDetails">
  <div class="form-group users">

    <input type="text" required="required" id="LeadEmailDetail0FirstName" value="" name="data[LeadEmailDetail][0][first_name]">
    <label for="LeadEmailDetail0FirstName">First Name</label>

    <input type="text" id="LeadEmailDetail0LastName" value="" name="data[LeadEmailDetail][0][last_name]">
    <label for="LeadEmailDetail0FirstName">First Name</label>

    <select id="LeadEmailDetail0CountryId" class="select-replace select2-offscreen" name="data[LeadEmailDetail][0][country_id]" tabindex="-1" title="Country">
      <option value="">Choose a country</option>
      <option value="2">SOUTHEASTERN EUROPE</option>
    </select>
    <label for="LeadEmailDetail0CountryId">Country</label>

    <input type="checkbox" id="LeadEmailDetail0PrimaryEmail" value="1" name="data[LeadEmailDetail][0][primary_email]">
    <label for="LeadEmailDetail0PrimaryEmail">Primary Email</label>
  </div ">
    	</div">
  <div id="MoreEmails"></div>
  <input type="submit" value="Add More" id="addMoreEmail">

在上面的代码输入类型文本和复选框工作正常(点击添加更多后添加动态字段),但我在下面的错误选择选项

TypeError: jQuery(...).attr(...) is undefined

1 个答案:

答案 0 :(得分:2)

您需要为jQuery(this).attr('name'))添加空检查。 JSFIDDLE

以下是修改后的JS代码块。

clone.find(':input').each(function() {
    if(jQuery(this).attr('name')) {
  var name = jQuery(this).attr('name').replace(0, counter);
  var id = jQuery(this).attr('id').replace(0, counter);
  jQuery(this).attr({
    'name': name,
    'id': id
  }).val(); }
});