Hasanul
Hasanul

Reputation: 43

Add table row after even number of <td>

I wanted to add row in my table after even number of

My input html is like this

<table id ="my_table">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
      </tr>
    </tbody>
</table>

And I want output like this

<table id ="my_table">
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td>
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>
    </tbody>
</table>

I tried with this, but didn't get the output correctly.

$("</tr><tr>").insertAfter($("td:odd"));

Not sure where I did the mistake.

Upvotes: 0

Views: 134

Answers (3)

Keith Nordstrom
Keith Nordstrom

Reputation: 354

First thing I've noticed is that $("") has the HTML open and close tags in the wrong order. But without seeing the rest of your code I don't know where you're going wrong.

Here's a fiddle that does what you need: https://jsfiddle.net/tsap/9vumxk5k/

(function() {
  var tbl = $("#my_table"), tr = tbl.find("tr:first");
  tbl.find("tr > td").each(function(i, item) {
    item = $(item);     
    if (i % 2 == 0) {
        tr = $('<tr>').appendTo(tbl);
    }
    if (i > 1) {
      item.remove();
      tr.append(item);
    }
  });
})();

Upvotes: 1

Neil
Neil

Reputation: 14313

This can be accomplished through looping over the odd elements wrapping them (with their even counter part).

$("td").unwrap();
$("td:nth-child(odd)").each(function () {
  $(this)
    .next()
    .andSelf()
    .wrapAll("<tr>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1" id="my_table">
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
      </tr>
    </tbody>
</table>

Upvotes: 1

HenryDev
HenryDev

Reputation: 4953

Here's a working solution. Hope it helps!

 $("table#my_table td").each(function (index) {
        var odd = isOdd((index + 1));
        if (odd) {
            $("table#my_table tbody").append($("<tr>").attr("align", "center"));
        }
        $("table#my_table tr").last().append($(this));
    });
    $("table#my_table tr").first().remove();

    function isOdd(num) {
        return num % 2;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table border = "1" id ="my_table">
    <tbody>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
        <td>5</td>
        <td>6</td>
    </tr>
    </tbody>
</table>

Upvotes: 1

Related Questions