uhura
uhura

Reputation: 2683

Tables: selected rows and loop through column JQuery&JavaScript

I have two questions :)

  1. Im using Jquery to select table rows and checkbox in the first column, how can I make 2 and 7 columns not clickable. I mean if you click 7 column's cell, it will not select checkbox and will not add 'selected' class.

    $('#tableID tbody tr')
        .filter(':has(:checkbox:checked)')
        .addClass('selected')
        .end()
        .click(function (event) {
            $(this).toggleClass('selected');
            if (event.target.type !== 'checkbox') {
                $(':checkbox', this).attr('checked', function () {
                    return !this.checked;
                });
            }
        });
    
  2. I'm using JavaScript to add all one column values, the script is working fine when the table doesn't have merged cells. How to make it work with merged cells.

_________                             _________
|_|_|_|_|                             |   |_|_|
|_|_|_|_|    script working           |___|_|_|     script doesn't work
|_|_|_|_|                             |_|_|_|_|
|_|_|_|_|                             |___|_|_|
function count() {

    var i;
    var sum=0;
    var table = document.getElementById("tableID");
    for (i=1;i<table.rows.length-1;i++) {
        sum += Number(table.rows[i].cells[3].innerHTML, 10);
    }
    document.getElementById('sum1').innerHTML = sum;
}

HTML code for the second part: http://jsfiddle.net/f4zH9/

Thanks

Upvotes: 0

Views: 2262

Answers (1)

cchana
cchana

Reputation: 4990

For part one, I found a different way to approach the problem:

$('#tableID tbody tr').each(function() {
    $('td', $(this)).click(function() {
        var index = $(this).index();
        if(index != 1 && index != 6) {
             $(this).parent().toggleClass('selected');
            if (event.target.type !== 'checkbox') {
                $(':checkbox', $(this).parent()).attr('checked', function () {
                    return !this.checked;
                });
            }
        }
    });
});​

This binds the click event to each cell and when the user clicks and checks the index of the cell, effectively checking what column you are clicking on. If the index is 1 or 6 (columns 2 or 7), then it does nothing. Here's a jsfiddle to show it in action: http://jsfiddle.net/cchana/vCVwv/2/

For part two of your question, there's a problem with your for loop, instead of:

for (i=1;i<table.rows.length-1;i++)

don't forget JavaScript starts counting from 0, you should have

for (i=0;i<table.rows.length;i++)

Created a jsfiddle to show it in action: http://jsfiddle.net/cchana/WRtZP/

Upvotes: 1

Related Questions