hmit
hmit

Reputation: 152

Weird dynamic table bug

My HTML:

<html>
    <head>
        <title>Table</title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        Row:<input id="gRow">Col:<input id="gCol"><button onClick="selectCell()">Find</button>
        <button onClick="addCol(); update();">Add Col</button><br/>
        <button onClick="addRow(); update();">Add Row</button><br/>
        <table id="tab">
            <tr class="rowtitle">
                <td></td>
                <th>1</th>
            </tr>
            <tr class="row row-1">
                <th class="coltitle">1</th>
                <td class="col col-1 edit"></td>
            </tr>
        </table>
        <script type="text/javascript">
            update();
            function update(){
                $('.edit').bind('dblclick', function() {
                    $(this).attr('contentEditable', true);
                }).blur(function() {
                    $(this).attr('contentEditable', false);
                });
            }
        </script>
    </body>
</html>

My Javascript:

nCol = 1,
nRow = 1;

var addCol = function(){
    nCol++;
    //add nes cols
    $('.rowtitle').append("<th class='title'>"+nCol+"</th>");
    for (var i = 0; i <= nCol; i++) {
        $('.row-'+i).append( "<td class = 'col col-" + i + " edit'></tr>" );
    };

};

var addRow = function(){
    nRow++;
    $("#tab").append( "<tr class = 'row row-" + nRow + "'></tr>" );

    $('.row-'+nRow).append("<th class='coltitle'>"+nRow+"</th>")
    //add nes cols
    for (var i = 1; i <= nCol; i++) {
        $('.row-'+nRow).append( "<td class = 'col col-" + i + " edit'></tr>" );
    };
};

var selectCell = function(){
    var col = $('#gCol').val(),
        row = $('#gRow').val();

    console.log('.row-'+row+' .col-'+col);
    $('.row-'+row+' .col-'+col).css('background-color', 'red');
};

When I used selectCell, I noticed it wasn't working. Upon inspection, I noticed the rows were doing what they should, a unique class each time. However, the columns would repeat multiple times within a row. How can I fix this?

To view what is acctually happening, create a bunch of rows and columns. Then type row 3 and col 5. This is what should happen. However, now type 1 and 1. Demo

Upvotes: 1

Views: 55

Answers (1)

tachyonflux
tachyonflux

Reputation: 20221

Your addCol is bugged. It should be:

var addCol = function () {
    nCol++;
    //add nes cols
    $('.rowtitle').append("<th class='title'>" + nCol + "</th>");
    $('.row').append("<td class = 'col col-" + nCol + " edit'></tr>");
};

Upvotes: 2

Related Questions