JS - jQuery dynamically adds and removes fields

I am trying to create a dynamically duplicated field using jQuery:

HTML Code (PHP):

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

JS was compiled 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 in order, but without changing the identifier, names and other attributes ( ID , NAME , FOR , etc.)

I tried to do: jQuery(this).attr('id')+i; and jQuery(this).attr('name')+i; but it does not work, as I suppose. infact, it doesn't work at all .:-)

How can I change the attr() this field while the theory does not exist yet?

By comments: fiddle here: http://jsfiddle.net/obmerk99/uZuWA/

+4
source share
1 answer

Proper use of the installation attribute

 $(this).attr('id', i); 

You should know what is best to use with clone() , as Ian suggested!

Demo with .clone

http://jsbin.com/oqalig/1/edit

+4
source

Source: https://habr.com/ru/post/1479114/


All Articles