Search code examples
javascriptjqueryhtmlcell

Store parent cell id in a list


I have a table which will output the id of the parent cell when it is clicked. How could I change this so it outputs more than one clicked cell. For example, right now if I click cell id '1' it will output 1. If I click cell '2' it will output 2 and so on. How can I make it so that it outputs '1,2,3' given that I've clicked on cell 1, 2 and 3. HTML:

<table>
    <tr>
        <td class='test' id='1'><img src='images/Dog.gif'/></td>
        <td class='test' id='2'><img src='images/Cat.gif'/></td>
        <td class='test' id='3'><img src='images/Mouse.gif'/></td>
        <td class='test' id='4'><img src='images/Human.gif'/></td>
    </tr>
</table>
<div id='output'></div>

JS:

$(document).ready(function() { 
    $('td.test').click(function() { 
        $('#output').text(this.id);
    });
});

Also, is there a way that if I clicked back on say, cell 2. it would remove '2' from the list.


Solution

  • Use an array to keep track of clicked items:

    $(document).ready(function() { 
        var clicked = [];
        $('td.test').click(function() {
            var found = clicked.indexOf(this.id);
    
            // Remove
            if(found !== -1) {
                clicked.splice(found, 1);
    
            // Add
            } else {
                clicked.push(this.id);
            }
            $('#output').text(clicked.join(','));
        });
    });
    

    http://jsfiddle.net/mx2kj/