Home > Back-end >  Connected Button between HTML and Typescript not working
Connected Button between HTML and Typescript not working

Time:01-04

i am currently trying myself on an exercise in Typescript and HTML. I found an online example of a connected button, which generates a table when clicked.

However I am not able to replicate this exercise:

HTML-Code:

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Title</title>
     <script src="script.ts"></script>
</head>
<body>
    <input type="button" value="Generate a table" onclick="generateTable()" />
</body>
</html>

Typescript Code:

function generateTable() {
    // creates a <table> element and a <tbody> element
    const tbl = document.createElement("table");
    const tblBody = document.createElement("tbody");

    // creating all cells
    for (let i = 0; i < 2; i  ) {
        // creates a table row
        const row = document.createElement("tr");

        for (let j = 0; j < 2; j  ) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            const cell = document.createElement("td");
            const cellText = document.createTextNode(`cell in row ${i}, column ${j}`);
            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <body>
    document.body.appendChild(tbl);
    // sets the border attribute of tbl to '2'
    tbl.setAttribute("border", "2");}

I am sorry if this is a stupid question, I just started out and wanted to learn something relevant.

CodePudding user response:

Make sure that you have compiled your TypeScript code to JavaScript. The HTML file is trying to execute the generateTable() function, which is written in TypeScript.

In order for the function to be executed in the browser, you need to first compile your TypeScript code to JavaScript. You can do this by running the following command in your terminal: tsc script.ts. This will generate a script.js file in the same directory as your script.ts file. You'll need to update the script tag in your HTML file to point to the script.js file instead of the script.ts file.

  • Related