0

A bit confused about how to target the following input with name client id, Tried lots of things but nothing worked !

So here I am :

<td class="main_contact">
    <input type="hidden" name="client_id" value="45">
    <label class="switch">
         <input type="checkbox">
         <span class="slider round"></span>
    </label>    
</td>

Here is what I tried as :

$('.switch input').on('change',function() {
    if (this.checked) {
        var parent_el = $(this).parents().eq(1).closest('input[name="client_id"]').val();
        // var client_id = $(parent_el[0]+' input[name="client_id"]').val();
        console.log(parent_el);
    } else {
        alert('Its UNCHECKED');
    }
});

NOTE : I want to get the value of input with name client_id while referencing it from the $(this) element so that I get only the current changed element input data not the data of every input there is?

Umair Shah
  • 2,305
  • 2
  • 25
  • 50
  • http://api.jquery.com/parents, http://api.jquery.com/parent or or http://api.jquery.com/closest. Either way, I suggest you read the jQuery documentation for simple queries like this. – Rory McCrossan Oct 29 '17 at 17:10

2 Answers2

1

You can just write .parent('selector'), but in this case, you want the parent without condition and then get a sibling. (You can use .siblings('selector') for that)

$('.switch input').on('change', function() {
  if (this.checked) {
    var parentVal = $(this).parent().siblings('input[name="client_id"]').val();
    console.log(parentVal);
  } else {
    alert('Its UNCHECKED');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="main_contact">
  <input type="hidden" name="client_id" value="45">
  <label class="switch">
    <input type="checkbox">
    <span class="slider round"></span>
  </label>
</td>
SourceOverflow
  • 1,960
  • 1
  • 8
  • 22
1

I prefer the .closest() method:

$(this).closest('.main_contact').find('[name="client_id"]').val();

Difference between jQuery parent(), parents() and closest() functions

Martijn
  • 15,791
  • 4
  • 36
  • 68