-1

I am a freshie in javascript and I am trying to make a table which depends on user input to add rows to a table

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <table id="myTable">
            <tr>
                <td>New Cell</td>
                <td>New Cell</td>
            </tr>
        </table>
        <br/>
        <button type="button" onclick="myFunction()">Try it</button>

        <script>
            function myFunction() {
                var input = window.prompt("Input number of rows", 1);
                for (var i = 0 ; i < parseInt(input,10); i++) {
                    var table = document.getElementById("myTable").insertRow(i);
                    for (var j = 0; j < table.rows[i]; j++) {
                        var cell1 = row.insertCell(0);
                        var cell2 = row.insertCell(1);
                        cell1.innerHTML = "NEW CELL1";
                        cell2.innerHTML = "NEW CELL2";
                    }
                }
            }
        </script>
    </body>
</html>

Take Input from the user using javascript to add rows dynamically

2
  • Answer on this link stackoverflow.com/questions/50113999/… can help you solve your problem. Commented Sep 14, 2019 at 11:57
  • Your code is not correct. The insertRow method doesnt return table but it returns a row. Commented Sep 14, 2019 at 14:47

1 Answer 1

0

You can modify your code like this: You can also refer to this like for reference: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_table_insertrow

<script>
        function myFunction() {
            var input = window.prompt("Input number of rows", 1);
            for (var i = 0 ; i < parseInt(input,10); i++) {
                var rowObj = document.getElementById("myTable").insertRow(i);
                for (var j = 0; j < table.rows[i]; j++) {
                    var cell1 = rowObj.insertCell(0);
                    var cell2 = rowObj.insertCell(1);
                    cell1.innerHTML = "NEW CELL1";
                    cell2.innerHTML = "NEW CELL2";
                }
            }
        }
    </script>
Sign up to request clarification or add additional context in comments.

Comments

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.