MrBuggy MrBuggy - 4 months ago 28
jQuery Question

Force click with trigger() on closest div

Hi I've got follow code:



$('.myInput').click(function() {
$('.addon').trigger('click');
});

$('.addon').click(function() {
console.log("Clicked");
});

.wrapper {
display: flex;
flex-direction: column;
}
.inputWithAddon {
display: flex;
margin-bottom: 10px;
}
input {
height: 20px;
}
.addon {
width: 26px;
height: 26px;
background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="inputWithAddon">
<input class="myInput">
<div class="addon"></div>
</div>
<div class="inputWithAddon">
<input class="myInput">
<div class="addon"></div>
</div>
<div class="inputWithAddon">
<input class="myInput">
<div class="addon"></div>
</div>
</div>





I would like to force a click with
trigger()
on my green div, when I clicked in the input. This should be on the div from the current clicked input (on the right side). At the moment, it calls the click for all the green divs (look at console). I would like just to do this for the div of the clicked input. I tried
closest()
:

$(this).closest('.addon').trigger('click');


It didn't work.

Any ideas?

Thanks.

Answer

Try using the sibling property of Jquery

$(this).siblings('.addon').trigger('click');