Use Javascript to "add the selected cells" in IE6

advertisements

In excel it is possible to highlight a range of cells and view the 'sum' in the 'status bar'.

Can this be done in IE6 using Javascript and a HTML table ?


Here is some code to get you started, using jQuery. Of course there are many ways you could improve on it.

(EDIT: One thing to check is how well it works in IE. I think you need to add something like this.onselectstart = function() {return false}; in the mousedown event handlers to disable text selection in IE, but I don't happen to have IE handy at the moment.)

<html>
<head>
<style type="text/css">
    .sel {background-color: #99ff33; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
$(function () {
    function col(cell) {
        return cell.parent().children("td").index(cell);
    }

    var start = null;

    function selectTo(cell) {
        if (start == null)
            return;
        $("td").removeClass("sel");
        var stop = $(cell);
        var tbl = start.closest("table");
        var rs = tbl.children("tbody").children("tr");
        var r0 = rs.index(start.parent()), c0 = col(start);
        var r1 = rs.index(stop.parent()), c1 = col(stop);
        var sum = 0;
        for (var i = r0; i <= r1; i++) {
            var cells = $(rs.get(i)).children("td");
            for (var j = c0; j <= c1; j++) {
                var cell = $(cells.get(j));
                cell.addClass("sel");
                sum += Number(cell.html());
            }
        }
        $("#total").html(""+sum);
    }

    $("table").mousedown(function () {
        return false;
    });

    $("td").mousedown(function () {
        start = $(this);
        selectTo(this);
        return false;
    });

    $("td").mouseover(function () {
        selectTo(this);
    });

    $("td").mouseup(function () {
        selectTo(this);
        start = null;
    });

    $("body").mouseup(function () {
        start = null;
    });
});
</script>

<body>
  <table>
    <tr> <td>1</td> <td>2</td> <td>3</td> <td>4</td> </tr>
    <tr> <td>2</td> <td>4</td> <td>6</td> <td>8</td> </tr>
    <tr> <td>3</td> <td>6</td> <td>9</td> <td>12</td> </tr>
  </table>
  <p>Total of selected elements: <span id="total"></span></p>
</body>

</html>

Demo here.