简体   繁体   English

无法在jQuery中选择选项动态字段

[英]Not working select option dynamic field in jquery

  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"> 

In above code input type text and checkbox working fine (adding dynamic fields after click add more) but im getting below error in case select option 在上面的代码中,输入类型的文本和复选框工作正常(单击“添加更多”后添加动态字段),但是在选择选项的情况下我收到以下错误消息

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

You need to add a null check for jQuery(this).attr('name')) . 您需要为jQuery(this).attr('name'))添加一个空检查。 JSFIDDLE JSFIDDLE

Following is the modified JS code block. 以下是修改后的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(); }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM