Reputation: 2280
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?
Upvotes: 0
Views: 113
Reputation: 16103
I prefer the .closest()
method:
$(this).closest('.main_contact').find('[name="client_id"]').val();
Difference between jQuery parent(), parents() and closest() functions
Upvotes: 1
Reputation: 2038
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>
Upvotes: 1