user1049961
user1049961

Reputation: 2736

jQuery - best way to add/remove form section dynamically

I have following form group:

<div id="edu_row1">
        <div class="form-group">
           <label class="sr-only" for="edu_row_1_name"><?php _e('Name','ja'); ?></label>
           <input type="text" class="form-control" name="edu_row[1][name]" value="<?php echo $edu_item['name']; ?>" id="edu_row_[1]_name" placeholder="<?php _e('Enter school name','ja'); ?>">
        </div>
        <div class="form-group">
           <label class="sr-only" for="edu_row_from_date_1"><?php _e('From date','ja'); ?></label>
           <input type="text" class="form-control" value="<?php echo $edu_item['from_date']; ?>" id="edu_row_date_1_from" name="edu_row[1][from]" placeholder="<?php _e('From date','ja'); ?>">
        </div>
        <div class="form-group">
            <label class="sr-only" for="edu_row_to_date_1"><?php _e('To date','ja'); ?></label>
            <input type="text" class="form-control" value="<?php echo $edu_item['to_date']; ?>" id="edu_row_date_1_to" name="edu_row[1][to]" placeholder="<?php _e('To date','ja'); ?>">
        </div>
        <input type="text" class="form-control" value="1" id="edu_row_<?php echo $i; ?>_id" name="edu_row[1][id]" placeholder="<?php _e('ID','ja'); ?>">
</div>

What would be the best way to be able to add/remove buttons to add another section with jQuery, with proper indexes? I tried using the code from http://bootsnipp.com/snippets/featured/dynamic-form-fields-add-amp-remove, but that seems way too compliacted.

Upvotes: 1

Views: 1903

Answers (1)

Xaver
Xaver

Reputation: 11662

var clone = $('#edu_row1').clone(),
    number = $('.edu_row').length+1;

//add new id to the clone
clone.attr('id', 'edu_row'+number)

//change label
.find('label').each(function(){
   $(this).attr('for', $(this).attr('for').replace('_1_', '_'+number+'_'));
});

//change inputs inside the form-group
clone.find('.form-group > input').each(function(){
   $(this).attr('id', $(this).attr('id').replace('_1_', '_'+number+'_'));
   $(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
});

//change latest input
clone.find('input.form-control').last().each(function(){
   $(this).attr('id', $(this).attr('id').replace('_1', '_'+number+''));
   $(this).attr('name', $(this).attr('id').replace('[1]', '['+number+']'));
   $(this).val(number);
});

//insert the clone after the last
clone.insertAfter('.edu_row:last');

This requires an additional class though:

<div id="edu_row1" class="edu_row">
    ...
</div>

Upvotes: 2

Related Questions