Wednesday, January 6, 2016

move elements up and down in list dropdown

The below example helps the developer to understand how to move the elements up and down in a list box. 

HTML code:
<div id="selected">
    <div><strong>Selected</strong></div>
    <div id="selected-items">
        <select multiple="multiple" id="selected-items-select">
            <option>one</option>
            <option>two</option>
            <option>three</option>
            <option>four</option>
        </select>
    </div>
</div>



<div id="priority">
    <div><input type="button" id="move-up" value=" ^ " /></div>
    <div><input type="button" id="move-down" value=" v " /></div>
</div>

Java script code :
$(document).ready(function() {
    $('#move-up').click(moveUp);
    $('#move-down').click(moveDown);
});
/* this method find the selected element and move the element one position up*/
function moveUp() {
    $('#selected-items select :selected').each(function(i, selected) {
        if (!$(this).prev().length) return false;
        $(this).insertBefore($(this).prev());
    });
    $('#selected-items select').focus().blur();
}

/* this method find the selected element and move the element one position down*/
function moveDown() {
    $($('#selected-items select :selected').get().reverse()).each(function(i, selected) {
        if (!$(this).next().length) return false;
        $(this).insertAfter($(this).next());
    });
    $('#selected-items select').focus().blur();
}


Created sample code in JSFIDDLE at http://jsfiddle.net/FBTVk/1/