Click here to Skip to main content
15,884,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<!DOCTYPE html> 
<html> 
<head> 
<meta charset=utf-8 /> 
<title>Create a table</title> 
<style type="text/css"> 
div {
background: red;  
margin: 5px;    
}

table {
 border: 2px solid black;   
}

td {
    padding: 10px;
 border: 1px solid lightgrey; 
}


</style> 
 
</head>

<body > 
<input type="text" id="tb1" value="2">
<input type="text" id="tb2" value="4">
<form> 
<input type="button" onclick="createTable()" value="Create the table"> 
</form>
</body>
</html>

<script>
function createTable() {
    var a, b, tableElem, rowElem, colElem;

    a = document.getElementById('tb1').value;
    b = document.getElementById('tb2').value;

    if (a == "" || b == "") {
        alert("Please enter some numeric value");
    } else {
        tableElem = document.createElement('table');

        for (var i = 0; i < a; i++) {
            rowElem = document.createElement('tr');

            for (var j = 0; j < b; j++) {
                colElem = document.createElement('td');
                //colElem.appendChild(document.createTextNode(j + 1));
                rowElem.appendChild(colElem);
            }

            tableElem.appendChild(rowElem);
        }

        document.body.appendChild(tableElem);

    }
}





</script>


What I have tried:

i dont know how can i do that with one cell because its in dom and not in html
Posted
Updated 28-Dec-19 5:31am

1 solution

how about something like (after adding the table into the document body):
JavaScript
$('td').click(function() {$(this).addClass('highlighted');});
This will cause any TD element to change colour when clicked; if you want to confine it to just the appended table, then add a unique ID attribute to the TABLE element and refer to that in the selector:
JavaScript
$('#addedTable td')....
(This requires you to include at least a basic version of JQuery to your page). You'll also need to add a class .highlighted with whatever visual styling you want for your highlighted cells.C
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900