javascripthtmljqueryjquery-selectors

Finding closest input in same cell multiple spans


I am having a hard time getting the closest input to the button clicked. Everything is on the same table cell. The button is inside a span and the input is inside 3 level span? Please see for reference

<td
  colspan="1"
  rowspan="1"
  data-record-id="9"
  class="r-field-number"
  data-field="miles"
  data-cellid="grid_cell_field7"
  data-pageid="1"
  data-signal-error-for="miles9"
>
  <span
    data-itemtype="grid_field"
    data-itemid="simple_grid_field10"
    data-pageid="1"
    data-record-id="9"
    data-field="miles"
    data-fieldname="miles"
    data-default-width=""
    data-editcontrol=""
  >
    <span id="edit9_miles">
      <span id="edit9_miles_0" class="bs-ctrlspan">
        <input
          id="value_miles_9"
          class="form-control"
          type="text"
          name="value_miles_9"
          placeholder=""
          value=""
        />
      </span>
    </span>
  </span>

  <span
    data-itemtype="text"
    data-itemid="text2"
    data-pageid="1"
    data-record-id="9"
    data-small=""
  >
    <a href="#" data-id="8541" class="btn btn-sm btn-primary get-miles"
      >Get Miles</a
    >
  </span>
</td>

enter image description here

I have tried

var input_id = $(this).closest('input').attr('id');
var input_id = $(this).closest('span').find('input').attr('id');

No luck, any help is greatly appreciate it


Solution

  • Everything is on the same table cell

    Traverse up to the <td> then find the <input>

    const input_id = $(this).closest('td').find('input[id]').attr('id');
    

    You definitely do not need jQuery for this

    // Add a delegated event listener at an appropriate level
    // document in this example
    document.addEventListener('click', (e) => {
      const btn = e.target.closest('a.get-miles');
      if (btn) {
        e.preventDefault();
        const input_id = btn.closest('td')?.querySelector('input[id]')?.id;
    
        console.log('input id:', input_id);
      }
    });
    <!-- your HTML, minified -->
    <table><tr><td class=r-field-number colspan=1 data-cellid=grid_cell_field7 data-field=miles data-pageid=1 data-record-id=9 data-signal-error-for=miles9 rowspan=1><span data-itemid=simple_grid_field10 data-itemtype=grid_field data-pageid=1 data-record-id=9 data-default-width=""data-editcontrol=""data-field=miles data-fieldname=miles><span id=edit9_miles><span id=edit9_miles_0 class=bs-ctrlspan><input class=form-control id=value_miles_9 name=value_miles_9 placeholder=""value=""> </span></span></span><span data-itemid=text2 data-itemtype=text data-pageid=1 data-record-id=9 data-small=""><a class="btn btn-primary btn-sm get-miles"data-id=8541 href=#>Get Miles</a></span></td></tr></table>