Search code examples
javascripthtmlhtml-tablewysiwyg

Table Issue in WYSIWYG Editor


I'm creating an HTML WYSIWYG editor from scratch and I have an issue when it comes to tables. Somehow, I'm able to create the pretended number of columns but only one row (without the heading). I'd be thankful if anyone could tell what's the issue.

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Text Editor</title>
</head>
<body>

        <div id="Ribbon">

<div id="Ribbon-3">
        <button class="RibbonBtn" id="TableButton" title="Insert Table"><i class="fas fa-table"></i></button>
        </div>

        </div>

        <div id="TextArea">
            <div id="WYSIWYG" contenteditable="true"></div>

        </div>

    </div>




</body>
</html>

JS

window.addEventListener("load",function(){

    $('#TableButton').click(function(){
        var colnum = prompt("Indicate the number of columns");
        var rownum = prompt("Indicate the number of rows");
        var table = "";
        var tablehead = "";
        var tablebodytext = "";
        for (var i = 0; i < colnum; i++) {
            tablehead += "<th>null</th>";
        }

        var tablebody = [];
        for (var i = 0; i < rownum; i++) {
            var tablebodyrow = "";
            for (var i = 0; i < colnum; i++) {
                tablebodyrow += "<td>null</td>";
            }
            tablebody += "<tr>" + tablebodyrow + "</tr>";
        }

        table = "<table><tr>" + tablehead + "</tr>" + tablebody+ "</table>";
        document.execCommand("insertHTML",false, table);
    });


},false);

enter image description here

I chose 5 columns and 4 rows, but instead it created 5 columns and only 1 row


Solution

  • I've found the error. Such a dumb mistake... I was using the same "i" var for the nested for loop and its parent loop.

    This is the right version:

    $('#TableButton').click(function(){
            var colnum = prompt("Indicate the number of columns:");
            var rownum = prompt("Indicate the number of rows:");
            var table = "";
            var tablehead = "";
            var tablebodytext = "";
            for (var i = 0; i < colnum; i++) {
                tablehead += "<th>null</th>";
            }
    
            var tablebody = [];
            for (var i = 0; i < rownum; i++) {
                var tablebodyrow = "";
                for (var i1 = 0; i1 < colnum; i1++) {
                    tablebodyrow += "<td>null</td>";
                }
                tablebody += "<tr>" + tablebodyrow + "</tr>";
            }
    
            table = "<table><tr>" + tablehead + "</tr>" + "<tbody>" + tablebody + "</tbody>" + "</table>";
            document.execCommand("insertHTML",false, table);
        });