Search This Blog

Google Analytics

Tuesday, February 26, 2013

jQuery: Move Up, Move Down, Delete Elements

The following article describes how to make use of jQuery to move elements up/down and also to delete them.

How it will look like

The JavaScript bit
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $(".moveDown").click(function() {
            $(this).closest("li").insertAfter($(this).closest("li").next());
            //$(this).parent().parent().insertAfter($(this).parent().parent().next());
        });
        $(".moveUp").click(function() {
            $(this).closest("li").insertBefore($(this).closest("li").prev());
            //$(this).parent().parent().insertBefore($(this).parent().parent().prev());
        });
        $(".deleteItem").click(function() {
            $(this).closest("li").remove();
        });
    });

    function getSequence() {
        var liIds = $('.olList li').map(function(i, n) {
            return $(n).attr('attr');
        }).get().join(',');

        alert(liIds);
    }
</script>

The HTML bit
<ol class="olList">
    <li attr="1">
        <span>Item 1</span>
        <span><a href="javascript:void(0)" class="moveUp">Move Up</a></span>  
        <span><a href="javascript:void(0)" class="moveDown">Move Down</a></span>  
        <span><a href="javascript:void(0)" class="deleteItem">Delete</a></span>
    </li>
    <li attr="2">
        <span>Item 2</span>  
        <span><a href="javascript:void(0)" class="moveUp">Move Up</a></span>  
        <span><a href="javascript:void(0)" class="moveDown">Move Down</a></span>  
        <span><a href="javascript:void(0)" class="deleteItem">Delete</a></span>
    </li>
    <li attr="3">
        <span>Item 3</span>  
        <span><a href="javascript:void(0)" class="moveUp">Move Up</a></span>  
        <span><a href="javascript:void(0)" class="moveDown">Move Down</a></span>  
        <span><a href="javascript:void(0)" class="deleteItem">Delete</a></span>
    </li>
</ol>
<br />
<input type="button" value="Get Sequence" onclick="getSequence()" />

No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.

Popular Posts