jQuery Sort Numeric (Solution)

Sort numeric with hidden HTML, problem solution.

by Salustiano Silva

HTML

<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<div id="table_container">
    <table id="products">
        <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>quantity</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

CSS

tr.row_selected td{
    background-color:red !important;
}
td > span{
    display:none;
}

JavaScript

jQuery.fn.dataTableExt.oSort["myNumeric-desc"] = function (x, y) {
    var myX = $(x).text().replace(/[^0-9.-]/g, ""),
        myY = $(y).text().replace(/[^0-9.-]/g, "");
    if (!myX) myX = -9999999999999;
    if (!myY) myY = -9999999999999;
    return myX - myY;
};

jQuery.fn.dataTableExt.oSort["myNumeric-asc"] = function (x, y) {
    return jQuery.fn.dataTableExt.oSort["myNumeric-desc"](y, x);
}

var oTable = $("#products").dataTable({
    "aaData": [
        [1, "Dinner", "<span>? 1</span>1"],
        [2, "Study", "<span>? 54</span>54"],
        [2, "Study", "<span>? -5</span>-5"],
        [3, "Sleep", "<span>? 6</span>6"],
        [4, "Sleep", "<span> ?</span>"],
        [5, "Sleep", "<span>3 ?</span>3"],
        [6, "Study", "<span>? 60</span>60"]
    ],
    "aoColumns": [{
        "sClass": "center",
        "bSortable": false
    }, {
        "sClass": "center",
        "bSortable": false
    }, {
        "sClass": "center",
        "bSortable": true,
        "sType": "myNumeric"
    }]
});