user1387989
user1387989

Reputation: 77

Failed to get a table cell

I have the following problem when wanting to get the cell of a table where a change event is not achieving its procurement.

Any idea how to get it , it would be well received .

<tr>
          <td>1</td>
          <td><div class="switch switch-small">
            <input name="op1" type="checkbox" checked />
          </td></div>
      </td></tr>

$("tbody tr td input:checkbox").change(function() {
    id = $(this).parent().parent().children().index(this.parentNode);
    alert(id);
});

enter image description here

Upvotes: 1

Views: 95

Answers (4)

Igwe Kalu
Igwe Kalu

Reputation: 14868

Your question is not clear, but I suppose you want to get the index corresponding to a radio input. As @Roko mentioned in his answer, your markup is wrong, it should be in the following form:

<tr>
    <td>1</td>
    <td>
        <div class="switch switch-small">
            <input name="op1" type="checkbox" checked />
        </div>
    </td>
</tr>

Finally to get index, 1, when input with name op1 changes, here's how you do that:

$("td input[type='checkbox']").on("change", function() {
    var trParent = $(this).parent().parent().parent();
    var id = $("tr").index(trParent);
    alert(id);
});

I hope that helps, or you may consider reviewing your question.

Upvotes: 1

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

jsBin demo

You cannot close a </div> after a </td>. Also you're closing 3 times a TD element. Please review your HTML markup immediately.

If you want to get the TD where you clicked the checkbox:

$("td :checkbox").change(function() {
    var TD = $(this).closest("td");
    alert(TD.index()); // or use TD.closest("tr").index(); // to get the TR index
});

Upvotes: 1

user1387989
user1387989

Reputation: 77

var cell = $(this).closest('td'); var cellIndex = cell[0].cellIndex

var row = cell.closest('tr'); var rowIndex = row[0].rowIndex;

Upvotes: 0

sodawillow
sodawillow

Reputation: 13176

Try a simpler

$(function() {
    $("table [type='checkbox']").on("change", function() {
        console.log($(this).parent().prev().html());
    });
});

jQuery selector meaning : "anything in the table having type=checkbox"

Upvotes: 0

Related Questions