Sortable ID Output

by TheFiddler

HTML

<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<div style="padding:10px">
    <button>Click to Update Names and activate sortable</button>
</div>
<ul id="deepwoods_meta_buybuttons-repeatable" class="deepwoods_metabox_repeatable">
    <li>
        <div class="handle"></div>Input:
        <input type="text" name="deepwoods_meta_buybuttons[2][thelink]"
        />
    </li>
    <li>
        <div class="handle"></div>Input:
        <input type="text" name="deepwoods_meta_buybuttons[0][thelink]"
        />
    </li>
    <li>
        <div class="handle"></div>Input:
        <input type="text" name="deepwoods_meta_buybuttons[1][thelink]"
        />
    </li>
</ul>

CSS

input {
    width:300px;
    padding:5px;
}
.handle {
    height:20px;
    background:#EAEAEA;
    cursor:move
}
li {
    border:1px solid green;
    margin:10px
}

JavaScript

var $list = $('.deepwoods_metabox_repeatable');
initDemo()
$('button').click(function () {
    updateNames($list);
    $list.sortable({
        stop: function (event, ui) {
            updateNames($(this))
        },
        handle: '.handle',       
    });
});

function updateNames($list) {
    $list.find('li').each(function (idx) {
        var $inp = $(this).find('input');
        $inp.each(function () {
            this.name = this.name.replace(/(\[\d\])/, '[' + idx + ']');
            /* demo fn to show name as value*/
            showNameAsValue(this)
        })
    });
}

function initDemo(){
    $('input').val(function(){
        return this.name
    })
        
}   

function showNameAsValue(el) {
    el.value = el.name;
}