How to get the row index in a HTML table

前端 未结 4 357
抹茶落季
抹茶落季 2021-01-14 08:10

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 t

相关标签:
4条回答
  • 2021-01-14 08:49

    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()
    
    0 讨论(0)
  • 2021-01-14 08:51

    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/

    0 讨论(0)
  • 2021-01-14 08:59

    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);
    });
    
    0 讨论(0)
  • 2021-01-14 09:07

    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();
    });
    
    0 讨论(0)
提交回复
热议问题