1

I want to generate click able table grid using javascript.

My code is not working.

  1. I created 2 text input fields for get values for row and column.
  2. Button that will call drawGrid() function onClick event.

     <input type="text" name="enter" class="enter" value="" id="inputX"/>
     <input type="text" name="enter" class="enter" value="" id="inputY"/>
     <input type="button" value="click" onclick="drawGrid();"/>
    
      <script language="JavaScript">          
      function drawGrid(){             
         document.write('<table border="1">');              
            var x_start = 1;
            var x_end = document.getElementById('inputX').value;
            var y_start = 1;
            var y_end = document.getElementById('inputY').value;
            // loop over all x values (rows) sequentally
            for( var x=x_start; x <= x_end; x++ ){
                // open the current row
                document.write('<tr>');
                // loop over all y values (cols) sequentally
                for( var y=y_start; y <= y_end; y++ ){
                    // write out the current x/y coordinate with a table cell
                    document.write('<td> x:'+x+' y:'+y+'</td>');
                }
                // end the current row
                document.write('</tr>');                    
                document.write('</table>');
            }
     }
    </script>
    

1 Answer 1

1

First, a couple of points I think are worth making:

  1. document.write is not the best tool for this job.
  2. (and far more serious) Have a look again at your nested for-loops. You perform the outside loop width number of times. In this loop you create a new row, add some cells, close the row and then close the table.

Read #2 again - that's right, you try to make width number of rows instead of height number of rows. You also finish the table each row (yet only start the table once)

Here's some code that uses the ability to create elements with JS objects (a opposed to js-created text strings)

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}

window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    byId('goBtn').addEventListener('click', onGoBtnClicked, false);
}

function onCellClicked(evt)
{
    alert( this.innerHTML );
}

function onGoBtnClicked(evt)
{
    byId('tblTgt').innerHTML = '';
    var nCols = byId('inputX').value;
    var nRows = byId('inputY').value;

    var tbl, curRow, curCell;
    tbl = newEl('table');
    var x, y;
    for (y=0; y<nRows; y++)
    {
        curRow = newEl('tr');
        tbl.appendChild(curRow);

        for (x=0; x<nCols; x++)
        {
            curCell = newEl('td');
            curCell.addEventListener('click', onCellClicked, false);
            curCell.innerText = "[" + x + "," + y + "]";
            curRow.appendChild(curCell);
        }
    }
    byId('tblTgt').appendChild(tbl);
}

</script>
<style>

</style>
</head>
<body>
    nCols:<input type="text" name="enter" class="enter" value="" id="inputX"/><br>
    nRows:<input type="text" name="enter" class="enter" value="" id="inputY"/><br>
    <button id='goBtn'>click</button>
    <hr>
    <div id='tblTgt'></div>
</body>
</html>
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you enhzflep. Its working now. but cells are not clickable.
@user3119557 - you're welcome. Sorry, I overlooked that. I've added a new function onCellClicked and have attached this as the event listener for the click event on each cell. Because I've attached the function via JS instead of writing it inline in the HTML, the this parameter points to the element itself - this allows us to use just one function for any number of cells. :)
One more thing. how can we toggle the color of the clicked cell (white & black). if black then it should be white and if white then it should be black.
You're welcome. Sure thing, I've updated the solution. Take note of (1) the css rule for elements with the class active and (2) the updated onCellClicked function. - Each element has a member classList - this allows you to do all kinds of manipulations on the list of classes that an element has, without resorting to string manipulation, like was once necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.