skip to Main Content

I am trying to find a column index or header name when my cursor is in QTY input field inside html table in any of the row. Please view screenshot below.

In this image my cursor is in Qty column, when I press enter I am not able to get the header name (QTY) or column index.

enter image description here

Following is the code to find index which is not working and always resulted zero. Any help would be appreciated, thanks.

 $('#table-id').on('keypress', function (ev) {
        debugger
        var keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode == '13') {
            var index = $(this).closest("td").index;
        }
    });

3

Answers


  1. $('#table-id').on('keypress', function (ev) {
            debugger
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if (keycode == '13') {
                var index = $(this).closest("td").index;
                var headerName = $('#table-id th').eq(columnIndex).text();
    
            }
        });
    

    .eq() is a jQuery method that allows you to select a specific element from a collection of elements based on its index. hope this helps

    Login or Signup to reply.
  2. There are some mistakes in the code. Here is the updated code:-

    $('#table-id').on('keypress', function (event) {
        var keycode = (event.keyCode ? event.which : '');
        if (keycode == '13') {
           var index = $(this).closest("td").index;
        }
    });
    
    1. You have "ev" as a parameter in the event handler function parameter, while you are using event inside the function. I have updated the parameter from ev to event.
    2. You are mixing javascript and jquery. In javascript, we can use event.keyCode for getting key code. While, in jQuery, we use event.which for getting key code. I have updated that line.
    Login or Signup to reply.
  3. $(document).on('keydown', 'input', function(event) {
      if (event.key === 'Enter') {
        const index = $(this).closest('td').index();
        const thText = $(this).closest('table').find('thead th').eq(index).text();
        console.log(index, thText);
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <thead>
        <tr>
          <th>1th</th>
          <th>2th</th>
          <th>3th</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td><input type="text" placeholder="1"></td>
          <td><input type="text" placeholder="2"></td>
          <td><input type="text" placeholder="3"></td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search