jQuery移动表行与输入和更改ID /名称

时间:2014-09-09 10:08:56

标签: javascript jquery forms input

我需要有一些按钮,用于在表格行内上下移动输入内容。 在移动中,我需要保证输入的名称和ID被更改 关于他们的新职位

我已经尝试过JSFiddle,但无法让它工作:http://jsfiddle.net/vaDkF/1194/

例如,我第一行向下移动有四处变化:

        <input type="text" id="id_1" name="id_1"/>
        <input type="text" id="test_1" name="test_1"/>

需要成为

        <input type="text" id="id_2" name="id_2"/>
        <input type="text" id="test_2" name="test_2"/>

但值必须保持不变只需要更改ID /名称。

这只是一个测试示例,在生产环境中我有20个输入 每行。

希望有人可以提供帮助。

2 个答案:

答案 0 :(得分:1)

尝试这样做:重新排列行后,调用一个函数,该函数将重新指定id和name到输入字段

$(document).ready(function(){
    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else {
            row.insertAfter(row.next());
        }
        reAssignIdAndName();
    });

    reAssignIdAndName = function(){
        $('table tr').each(function(index){
            $(this).find('td:eq(2) input').each(function(){
            //id of input element
            var id = $(this).attr('id');
            //get index of underscrore
            var underScoreIndex = id.indexOf('_');
            //take id till underscore and append your index+1 value
            id = id.substring(0,underScoreIndex+1)+(parseInt(index)+1);
            //assigne new id and name
            $(this).attr('id',id); 
            $(this).attr('name',id);                
            });
        });
    };
});

<强> Demo

答案 1 :(得分:0)

这适用于仅为移动的2行重新分配位置:

jQuery(document).ready(function($){
$(".up,.down").click(function(){
    var $this = $(this),
        row = $this.parents("tr:first");

    if ($this.is(".up")) {
        if (row.parent().find("tr:first").get(0) !== row.get(0)) {
            reAssignPosition(row.prev().find('input'));
            row.insertBefore(row.prev());
            reAssignPosition(row.find('input'), true);
        }
    } else {
        if (row.parent().find("tr:last").get(0) !== row.get(0)) {
            reAssignPosition(row.next().find('input'), true);
            row.insertAfter(row.next());
            reAssignPosition(row.find('input'));
        }
    }
});

function reAssignPosition($elt, up) {
    var $row = $elt.parents("tr:first"),
        oldPosition = parseInt($row.find('input').attr('id').replace(/(id|test)_/, '')),
        newPosition, newId, newName, input = $row.find('input');    
    if (up) newPosition = oldPosition - 1;
    else newPosition = oldPosition + 1;
    $elt.each(function() {
        this.id = this.id.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
        this.name = this.name.replace(/(id|test)_(.*)/, "$1_" + (newPosition));
    });
}

});

我确信,有些重构可以完成。