1

I have a dynamic form that allows fields to be added and deleted dynamically with the help of jquery. The existing fields are autopopulated from values in mysql table. The add button adds a new input field while the delete button removes an input field. The fields loaded with values from the db are tagged with data-saved attributed. Now my dilemma is focused in the delete button. How can I delete new sections that are not tagged with data-saved attribute? EXAMPLE

JQUERY

$(document).ready(function () {
    $('#btnAdd').click(function () {
        var $clones     = $('#input_table tr'),
            num         = $clones.size() + 1,
            next_num    = parseInt($clones.last().find('input[name^="person_id"]').val()) + 1,
            $template   = $clones.first(),
            newSection  = $template.clone().attr('id', 'pq_entry_'+num),
            person_id   = 'person_id_'+num;
            person_fname = 'person_fname_'+num;
            person_status = 'person_status_'+num;

        newSection.removeAttr('data-saved');

       // clear out all sections of new input
        newSection.find('input').val('');
        newSection.find('select').val([]);

        newSection.find('input[name^="person_id"]').attr({
            'id': person_id,
            'name': person_id
        }).val();
        newSection.find('input[name^="person_fname"]').attr({
            'id': person_fname,
            'name': person_fname,
            'placeholder' : 'Person #'+num+' First Name'
        }).val();
        newSection.find('select').attr({
            'id': person_status,
            'name': person_status
        }).val(next_num);
        newSection.find('input[type="button"]').attr('data-ident', next_num);


        $('#input_table').append(newSection);
        $('#btnDel').prop('disabled', '');
        if (num == 100) $('#btnAdd').prop('disabled', 'disabled');
    });

    $('#btnDel').click(function () {
        var num = $('.clonedSection').length; // how many duplicate input fields we currently have
        $('#pq_entry_' + num).remove(); // remove the last element

        // enable the "add" button
        $('#btnAdd').prop('disabled', '');

        // if only one element remains, disable the "remove" button
        if (num - 1 == 1) $('#btnDel').prop('disabled', 'disabled');

    });

    $('#btnDel').prop('disabled', 'disabled');
});

HTML

<tbody id="input_table" >
    <tr id="pq_entry_1" class="clonedSection" data-saved="1">
        <td><input type="text" name="person_id" value='1' readonly /></td>
        <td>
        <input id="person_id_1" name="person_id_1" type="text" value='1'/>
        <input id="person_fname_1" name="person_fname" placeholder=" First Name" type="text" value='James'/>
        </td>
        <td>
        <select id="person_status_1" name="person_status_1"></select>
        </td>
    </tr>
    <tr id="pq_entry_2" class="clonedSection" data-saved="2">
        <td><input type="text" name="person_id" value='2' readonly /></td>
        <td>
        <input id="person_id_2" name="person_id_2" type="text" value='2'/><input id="person_fname_2" name="person_fname" placeholder=" First Name" type="text" value='Cynthia'/>
        </td>
        <td>
        <select id="person_status_2" name="person_status_2"></select>
        </td>
    </tr>
</tbody>
<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='Delete New Field' /></br>

2 Answers2

1

From

$('#pq_entry_' + num).remove(); // remove the last element

Change into

var toDelete = $('#pq_entry_' + num).not('[data-saved]');

if (toDelete.length) {
    // Last one wasn't a db-entry
    toDelete.remove();

    // enable the "add" button
    $('#btnAdd').prop('disabled', '');

    // if only one element remains, disable the "remove" button
    if ($('.clonedSection:not([data-saved])').length == 0) 
        $('#btnDel').prop('disabled', 'disabled');
}

Working example: http://jsfiddle.net/az9LQ/

Peter van der Wal
  • 11,141
  • 2
  • 21
  • 29
0

You can simplify it a lot:

  • Add a <script type="text/template"> element which can hold the HTML to be appended each time (it won't be visible on the page). I've substituted $1 for the row number which you are dynamically updating and all occurrences of $1 can be replaced in a single shot (and if you want to replace other values then you can extend this and use $2, $3, ... $n for multiple substitutions).
  • Set up various static variables outside the 'click' handlers including an addedRows array to store the rows as they are added.
  • In the 'add' handler:
    • Create the row from the template, replacing $1 with the row number;
    • Store the row in an addedRows array for later use in the 'delete' handler;
    • Dynamically update elements as needed; and
    • Update the buttons.
  • In the 'delete' handler:
    • The addedRows array stores all references to the dynamically added rows so just pop() the last row from the array and remove() it;
    • Update the buttons.

JSFIDDLE

HTML:

<table>
    <tbody id="input_table" >
    <tr id="pq_entry_1" class="clonedSection" data-saved="1">
        <td><input type="text" name="person_id" value='1' readonly /></td>
        <td>
        <input id="person_id_1" name="person_id_1" type="text" value='1'/>
        <input id="person_fname_1" name="person_fname" placeholder=" First Name" type="text" value='James'/>
        </td>
        <td>
        <select id="person_status_1" name="person_status_1"></select>
        </td>
    </tr>
    <tr id="pq_entry_2" class="clonedSection" data-saved="2">
        <td><input type="text" name="person_id" value='2' readonly /></td>
        <td>
        <input id="person_id_2" name="person_id_2" type="text" value='2'/><input id="person_fname_2" name="person_fname" placeholder=" First Name" type="text" value='Cynthia'/>
        </td>
        <td>
        <select id="person_status_2" name="person_status_2"></select>
        </td>
    </tr>
</tbody>
</table>
<input type='button' id='btnAdd' value='add another Person' />
<input type='button' id='btnDel' value='Delete New Field' /></br>
<script type="text/template" id="template">
    <tr id="pq_entry_$1" class="clonedSection">
        <td><input type="text" name="person_id" value="$1" readonly /></td>
        <td>
            <input id="person_id_$1" name="person_id_$1" type="text"/>
            <input id="person_fname_$1" name="person_fname" placeholder="Person #$1 First Name" type="text" />
        </td>
        <td>
            <select id="person_status_$1" name="person_status_$1"></select>
        </td>
    </tr>
</script>

JavaScript:

$(document).ready(function () {
    var template       = $('#template' ).html(),
        $input_table   = $( '#input_table' ),
        addedRows      = [],
        num_saved_rows = $('#input_table tr').length;


    $('#btnAdd').click(function () {
        var row = $( template.replace( /\$1/g, num_saved_rows + addedRows.length + 1 ) )
                    .appendTo( $input_table );
        addedRows.push( row );
        $('#btnDel').prop('disabled', num_saved_rows + addedRows.length == 100 );
        // Not sure what you are doing with the 'select' element but you can
        // dynamically update the attributes of any element like this:
        $( 'select', row ).val( '' );
    });

    $('#btnDel').click(function () {
        if ( addedRows.length )
        {
            addedRows.pop().remove();
            $('#btnAdd').prop('disabled', false);
            $('#btnDel').prop('disabled', !addedRows.length);
        }
    });

    $('#btnDel').prop('disabled', 'disabled');
});

Not sure what you are trying to do with the select element as it has no OPTION children.

MT0
  • 143,790
  • 11
  • 59
  • 117