atarixdev
atarixdev

Reputation: 13

Selecting element which .each() function runs on

I've this piece of code but am getting that elem is not defined. also tried this and $(this) but got the document instead.

I should mention that $('.listop') is an array of jquery objects (that is why I use each). before each listop element their is a radioOption element and I need that for each of them, when a person click on "listop", the "radioOption" will get checked.

let inputs = $('.listop');
$(document).ready(function() {
  inputs.each(function(int, elem) {
    elem.click(function() {
      elem.closest('.radioOption').prop('checked', true);
    });
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
  <td>
    <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
  <td> לנמען יחיד</td>
  <td>
    <div id="lonly" class="listop" style="display: inline;">
<input type="text" name="mobile">

Upvotes: 0

Views: 43

Answers (1)

mplungjan
mplungjan

Reputation: 178403

I assume you mean this

  1. Find the tr parent of the input
  2. find the checkbox with class .radioOption in that row and check it

NOTE, the event handler will work on ALL .listop inputs and ONLY check the checkbox in the same row

$(function() {
  $(".listop input").on("click",function() {
      $(this).closest("tr").find('.radioOption').prop('checked', true);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" class="radioOption" name="distribution[only]" value="6" data-id="lonly"></td>
    <td> לנמען יחיד</td>
    <td>
      <div id="lonly" class="listop" style="display: inline;">
        Mobile: <input type="text" name="mobile">
      </div>
    </td>
  </tr>
</table>

Upvotes: 2

Related Questions