Dev DOS
Dev DOS

Reputation: 1068

How to get the row index in a HTML table

I'm trying to update a database users table. I made an HTML table which contains the data of the users in my database. this HTML table contains 3 columns and in each row there is a button. when I click this button I should update the users database table with the information contained in the input and select field in the cells of the html table. my html code is:

<tr>
  <td><input type="text" name ="name"/></td>
  <td>
      <select name="select_job">
         <option value="1"> Engineer </option>
         <option value="2"> Doctor </option>
      </select>
  </td>
  <td><button>update </button></td>
</tr>

I tried to get the number of the rows on which the update button was clicked and then to get the data in each column but I failed . my js code is:

$("button").click( function() {
 var $row = $(this).parent().parent(); //tr
  var $columns = $row.find('td');
  $.each($columns, function(i, item) {

   values = values + 'td' + (i ) +':<br/>';


});

 });

How can I get the data (inpt text, selected item) in the row on which I clicked the button?

Upvotes: 3

Views: 38504

Answers (4)

Jitendra Pancholi
Jitendra Pancholi

Reputation: 7562

You can use parents() function for the same.

var tr = $(this).parents('tr');

this would give your row on which button was clicked.

<tr>
  <td><input type="text" name ="name"/></td>
  <td>
      <select name="select_job">
         <option value="1"> Engineer </option>
         <option value="2"> Doctor </option>
      </select>
  </td>
  <td><button>update </button></td>
</tr>


$("button").click(function () {
    var $row = $(this).parents('tr:first');

    var txt = $row.find('input[type=text]').val();
    var salVal = $row.find('select:selected').val();

    alert(txt+' '+salVal);
});

Upvotes: 1

scripto
scripto

Reputation: 2297

May be something like the code below will help you to get the required information.

$("button").click(function () {
    var $row = $(this).parent().parent(); //tr
    var $columns = $row.find('td');
    var rowIndex = $row.index();
    var values = new Array();
    for (var i = 0; i < $columns.length - 1; i++) {
        var item = $columns[i];
        values.push($(item).children().val());
    }
    alert(JSON.stringify(values));
});

http://jsfiddle.net/X4mMw/

Upvotes: 1

Adil
Adil

Reputation: 148180

You can use closest('tr') to get the row for current button and use index() to get the index of the row.

Live Demo

$(this).closest('tr').index()

Upvotes: 2

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

You can use like this

$("button").click(function () {
    var inputValue = $(this).closest("tr").find("input[type=text]").val();
    var selectValuse = $(this).closest("tr").find("[name='select_job']").val();
    var index = $(this).closest("tr").index();
});

Upvotes: 6

Related Questions