I am trying to make a dynamically duplicated field with jQuery :
The HTML (PHP) code :
<div id="widget_dup">
<p>
<textarea class="code" cols="50" rows="5" id="o99_brsa_settings[brsa_dash_wdgt_content]" name="o99_brsa_settings[brsa_dash_wdgt_content]" value="<?php //echo $o99_brsa_options['brsa_dash_wdgt_content']; ?>"/><?php
echo $o99_brsa_options['brsa_dash_wdgt_content'];
?></textarea>
<label class="description" for="o99_brsa_settings[brsa_dash_wdgt_content]">
</br><?php _e('Content for 1st widget', 'o99-brsa-domain'); ?>
</label>
</p>
</div>
<div id="addScnt">add</div><div id="remScnt">remove</div>
the JS was assembled from some snippets I found :
<script type="text/javascript">
//http://jsfiddle.net/obmero99/ZD9Ky/
// <![CDATA[
jQuery(function() {
var scntDiv = jQuery('#widget_dup');
var prevDiv = scntDiv.html();
var i = jQuery('#widget_dup p').size() + 1;
jQuery('#addScnt').live('click', function() {
jQuery(prevDiv).appendTo(scntDiv);
i++;
//alert (prevDiv);
return false;
});
jQuery('#remScnt').live('click', function() {
if( i > 2 ) {
jQuery(this).parents('p').remove();
i--;
}
return false;
});
});
// ]]>
</script>
The problem is that this code will duplicate the fields ok, but without changing the ID , names and other attributes ( ID
, NAME
,FOR
etc.. )
I have tried to do : jQuery(this).attr('id')+i;
and jQuery(this).attr('name')+i;
, but it does not work as I intend. infact, it does not work at all. :-)
How can I modify the attr()
of the field while is theory it does not exists yet ?
As per comments: fiddle is here: http://jsfiddle.net/obmerk99/uZuWA/
The correct use of setting attribute is
$(this).attr('id', i);
You should know, that the better use is with clone()
, as Ian suggested!
Demo with .clone