Jquery ui sortable on table rows

sortable on table rows

by ramesh valasa

HTML

<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<table id="sortableContainer" cellpadding="0" cellspacing="0" border="1">

   <thead>
     <tr>
          <th>ID </th>
          <th>Location</th>
          <th>Preference</th>
      </tr>
    
   </thead>
   <tbody>
    <tr>
        <td>1</td>
        <td> Goa</td>
        <td>1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Mahabaleshwar</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Kerala</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Kashmir</td>
        <td>4</td>
    </tr>
    <tr>
        <td>5</td>
        <td>Ooty</td>
        <td>5</td>
    </tr>
    <tr>
        <td>6</td>
        <td>Simla</td>
        <td>6</td>
    </tr>
    <tr>
        <td>7</td>
        <td>Manali</td>
        <td>7</td>
    </tr>
    <tr>
        <td>8</td>
        <td>Darjeeling</td>
        <td>8</td>
    </tr>
    <tr>
        <td>9</td>
        <td>Nanital</td>
        <td>9</td>
    </tr>
    </tbody>
</table>

CSS

table th, table td
    {
        width: 100px;
        padding: 5px;
        border: 1px solid #ccc;
    }
    .selected
    {
        background-color: #666;
        color: #fff;
    }
    
    tr {
      cursor: pointer;
    }

JavaScript

$(function () {
    $("#sortableContainer tbody").sortable({
        items: 'tr',
        cursor: 'pointer',
        axis: 'y',
        dropOnEmpty: false,
        start: function (e, ui) {
            ui.item.addClass("selected");
        },
        stop: function (e, ui) {
            ui.item.removeClass("selected");
            $(this).find("tr").each(function (index) {
                if (index > 0) {
                    $(this).find("td").eq(2).html(index);
                }
            });
        }
    });
});