动态删除没有唯一属性的输入字段

时间:2013-12-07 22:23:05

标签: javascript jquery

我有一个动态表单,允许在jquery的帮助下动态添加和删除字段。现有字段是从mysql表中的值自动填充的。 add button添加新输入字段,而delete button删除输入字段。从db中加载值的字段标记为data-saved个归属。现在我的困境集中在delete button。如何删除未使用data-saved属性标记的新部分? 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 个答案:

答案 0 :(得分:2)

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

转入

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');
}

工作示例:http://jsfiddle.net/az9LQ/

答案 1 :(得分:0)

你可以简化它:

  • 添加一个<script type="text/template">元素,每次都可以保存要添加的HTML(在页面上不可见)。我已将$1替换为您正在动态更新的行号,并且所有出现的$1都可以一次性替换(如果您想要替换其他值,则可以对此进行扩展并使用对于多次替换,$2$3,... $n
  • 在“点击”处理程序之外设置各种静态变量,包括addedRows数组,以便在添加行时存储这些行。
  • 在'add'处理程序中:
    • 从模板创建行,将$1替换为行号;
    • 将行存储在addedRows数组中,以便以后在“删除”处理程序中使用;
    • 根据需要动态更新元素;和
    • 更新按钮。
  • 在'删除'处理程序中:
    • addedRows数组存储了对动态添加的行的所有引用,因此只有pop()数组的最后一行和remove()它;
    • 更新按钮。

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');
});

不确定您要对select元素做什么,因为它没有OPTION个孩子。