Home > Software engineering >  How can i make a table on a website using js by taking user inputs of number of rows and columns wit
How can i make a table on a website using js by taking user inputs of number of rows and columns wit

Time:12-13

try to make it using vanila html css js/////tq


function getit(){
    let rows = document.querySelectorAll("input")[0].value
    let col = document.querySelectorAll("input")[1].value
    let thead=document.querySelectorAll("input")[2].value
    let tablerow = "<td>" thead "</td>"
    let tablecol = "<tr> </tr>"

    // console.log(rows,col)
    // prevhtml=document.querySelectorAll("table")[0].innerHTML
    let prevrow="";
    
    for (let i = 0; i<rows; i  ) {
        prevrow=prevrow tablerow  
    }
    console.log(prevrow)

    let prevcol="";
    for (let i = 0; i<col; i  ) {
        prevcol=prevcol "<tr>" prevrow "</tr>"
    }
    console.log(prevcol)

    document.querySelectorAll("table")[0].innerHTML=prevcol;  
}


Don't judge please...Learned js yesterday only I have been working on this since yesterday ...

CodePudding user response:

Instead of using let tablecol = "<tr> </tr>" you can use tr = tbl.insertRow() and nested loops:

tbl = document.querySelectorAll("table")[0]
for (let i = 0; i<rows; i  ) {
    tr = tbl.insertRow();
    for (let i = 0; i<col; i  ) {
        const td = tr.insertCell();
    }
    tbl.appendChild(tr);
}

CodePudding user response:

<body>
    <div id="hello">
        <!-- your generated table code will be avaiable here -->
    </div>

    <script>

        // str is a variable that will be used for generating table contnet as string        
        let str="<table border='1'>";

        //to take input from user for number of rows requried by the user    
        let row=parseInt(prompt("Enter Number of rows you want to add in your table : "));

        //to take input from user for number of cols required by the user
        let cols=parseInt(prompt("Enter Number of cols you want to add in your table : "));

        //this loop will run for number of rows value entered by the user
        for(let i=1;i<=row;i  ){
            str=str "<tr>"

            //this loop will run for number of cols value entered by the user    
            for(let j=1;j<=cols;j  ){

                //data variable is used here to take input from the user for every cell of the table
                let data=prompt("Enter data in row " i " and col " j);
                str=str "<td>" data "</td>";
            }
            str=str "</tr>";
        }

        str=str "</table>";

        //here we are takeing the div elemnt and putting table inside the div element with id hello
        document.getElementById('hello').innerHTML=str;
    </script>
</body>
  • Related