开发者

How would I fill an empty cell in a HTML table with another word using JavaScript?

开发者 https://www.devze.com 2023-02-18 00:29 出处:网络
I\'m trying to make a table that has 3 cells to a ro开发者_如何学运维w, and into those three cells, I have a string that I get from a textbox from a HTML form that I created an array from. I\'m using

I'm trying to make a table that has 3 cells to a ro开发者_如何学运维w, and into those three cells, I have a string that I get from a textbox from a HTML form that I created an array from. I'm using JavaScript to do this, and I have it to where I have each word in their own cell, but if there is an empty cell, it won't create a cell. How can I fill that empty cell with another word like "empty".

This is what I have so far.

arrays=tx_val.split(' ');
table="< table border='1' bgcolor=gray>"
for(x=0;x< arrays.length-2;x=x+3)
{
    if(x<arrays.length-2)
    {
        table=table+"< tr>< td>"+arrays[x]+"< /td> <td>"+arrays[x+1]+ 
                "< /td>< td>"+arrays[x+2]+"</td><td>";
    }
    else
    {
            table=table+"< /tr>< /table>"
    }

}


|| 'empty'

as in

(arrays[x] || 'empty')

or

var empty = '--empty--';
if(x) table += "<tr><td>" + (arrays[x] || empty) + "</td> " + (arrays[x+1] || empty) + "</td><td>" + (arrays[x+2] || empty) + ""


There are errors in your logic that might be causing you problems:

for(x=0;x< arrays.length-2;x=x+3)
{
    if(x<arrays.length-2)

Based on the for loop, the if statement will always evaluate to true. As such, for every iteration, you are adding a table row without an ending tr element and you are adding a table cell without an ending td element. The result will be ill-formed HTML that might not be rendering as you desire, even if you get some 'empty' value put in a cell.


Try this:

arrays = tx_val.split( ' ' );
table = "< table border='1' bgcolor=gray>";
currItem = 0;
for( x = 0; x < Math.ceil( arrays.length / 3 ); x = x + 1 )
{
    table = table + "<tr>";

    for( y = 0; y < 3; y = y + 1 )
    {
        if( arrays[currItem] == "" )
        {
            displayItem = "";
        }
        else
        {
            displayItem = arrays[currItem];
        }
        table = table + "<td>" + displayItem + "</td>";

        currItem = currItem + 1;
    }

    table = table + "</tr>";
}

Basically, I changed the loops to form the table code per row first, then per column. The outer for loop is the one responsible for adding code for each row. The Math.ceil( arrays.length / 3 ) formula determines the number of rows the table should have depending on the number of values in the array. The inner for loop creates 3 cells for each row.

If you want to change the dimensions of the table want to create you can just change the divisor in the Math.ceil function in the outer loop as well as the number used in the condition in the inner loop ( y < 3 ).

0

精彩评论

暂无评论...
验证码 换一张
取 消