javascript - JQuery change id attribute of elements -


i have drag , drop thing uses clone. having problem date clone though because of datepicker. therefore, need make sure each cloned datepicker has unique id. cloned element looks following

<div data-type="date" class="form-group">     <label class="control-label col-sm-5" for="dateinput">date input:</label>     <div class="col-sm-3">         <input type="text" name="dateinput[]" class="form-control date_picker" id="dateinput">     </div> </div> 

so if clone 2 date inputs, have 2 of above. on submit, clean of cloned html, doing things removing data-type. @ stage, if there cloned date input, need give unique id. @ moment doing this

$("#content").find(".form-group").each(function() {     var html = $(this).attr('class', 'form-group')[0].outerhtml.replace(/ data-(.+)="(.+)"/g, "");     var input = $(this).find('input');     var = 0;     if(input.attr('id') == 'dateinput') {         alert("test");         input.attr("id",'dateinput' + i).datepicker();         i++;     }     console.log(html);     dataarray.push(html); }); 

the test alert fires twice should if clone 2 date inputs. however, id attributes not seem change when output html console. have set following fiddle demonstrate id of element not changing.

any advice on getting change appreciated.

thanks

try defining dataarray, i outside out submit event, .each() , using .map() , .get() , .attr(function() {index, attr}) , .outerhtml

$(function() {     // define `i` , `dataarray`     var = 0, dataarray = [];     $('#content').submit(function(event) {         event.preventdefault();         $("#content").find(".form-group").each(function() {           var html = $(this).attr('class', '.form-group')[0]                      .outerhtml.replace(/ data-(.+)="(.+)"/g, "");           dataarray.push($(html).map(function(_, el) {                // adjust `input` `id` here , return `input` string              return $(el).find("input").attr("id", function(_, id) {               return id + (++i)                             })[0].outerhtml           }).get()[0])         });            $("#output")[0].textcontent = dataarray.join(" ");         console.log(dataarray)     }); }); 

jsfiddle https://jsfiddle.net/mlgrfzal/2/


Comments