Wednesday, July 20, 2011

Selected TD of TR of TABLE class style change

Horizontal

<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-1.4.2.min.js"></script>
<style>
.btn { background-color:red; }
</style>
</head>
<body>
<script type="text/javascript">
$(function(){
    var $firstClicked = false;
    var $trs = $("#table1 tr");
    $trs.each(function(indx,tr){
        var $tr_childs = $(tr).children();
        $tr_childs.click(function(){
                //$(this) is current td
                $td_indx = $(this).index();
                if(!$firstClicked){
                    $firstClicked = true;
                } else {
                    $firstClicked = false;
                    $tr_childs.filter(function(ii){
                        return $first_td_indx <= ii && ii <= $td_indx;
                    }).addClass("btn");
                }
                $first_td_indx = $td_indx;
        });
    });   
});
</script>
<table border="1" id="table1">
<tbody>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
</tbody>
</table>
</body>
</html>

 Vertical

<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-1.4.2.min.js"></script>
<style>
.btn { background-color:red; }
</style>
</head>
<body>
<script type="text/javascript">
$(function(){
    var $firstClicked = false;
    var $trs = $("#table1 tr");
    var $tds = $("#table1 tr td");
    $tds.click(function(){
        //$(this) is current td
        $tr_indx = $(this).parent().index();
        $td_indx = $(this).index();
        if(!$firstClicked){
            $firstClicked = true;
        } else {
            $firstClicked = false;
            $trs.filter(function(ii){
                return $first_tr_indx <= ii && ii <= $tr_indx;
            }).find("td:eq(" + $first_td_indx + ")").addClass("btn");
        }
        $first_td_indx = $td_indx;
        $first_tr_indx = $tr_indx;
    });   
});
</script>
<table border="1" id="table1">
<tbody>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
<tr>
    <td><input type="button" value="1"></td>
    <td><input type="button" value="2"></td>
    <td><input type="button" value="3"></td>
</tr>
</tbody>
</table>
</body>
</html>

No comments: