Cybermonk
Cybermonk

Reputation: 524

closest in jQuery with class selector

I'm using jQuery 1.12.4 to set get the value of the closest preceding element using class selector. I'm unable to select the closest element.

$(function() {
  $("[class='quickSelect']").blur(function() {
    var obj = $(this);
    alert($(this).parent());
    // alert($(this).closest("[class~='endDateField']")); 	
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td align="right">
      Start Date
    </td>
    <td>
      <input type="text" name="debitStartDate" value="" class="dateField startDateField">
    </td>
    <td align="right">
      End Date
    </td>
    <td>
      <input type="text" name="debitEndDate" value="" class="dateField endDateField">
    </td>


    <td class="debitApportioner" style="align:right">
      Quick Select
    </td>
    <td class="debitApportioner" colspan="2">
      <select class="quickSelect">
          <option> SELECT  </option>
          <option> JANUARY  </option>
          <option> FEBRUARY  </option>
          <option> MARCH  </option>
      </select>
      <input class="quickSelect" type="text" />
    </td>
  </tr>


</table>

Upvotes: 1

Views: 713

Answers (1)

Pete
Pete

Reputation: 58462

Try this:

$(".quickSelect").blur(function() {
    var obj = $(this);
    obj.closest('tr').find('.endDateField');  // will find the endDateField in the current row
  });

closest() only traverses up the trees ancestors and stops at the first element that matches the selector so the above says find the closest ancestor tr to the input then find any endDateField inside that tr

Upvotes: 2

Related Questions