Reputation: 571
...This has been asked a bunch of times, but I still cannot solve my problem.
I have a list of elements, created dynamically, defined by class 'box', as follows:
<div class="box">
<button onclick="buttonFunction(element.inputBox)"></button>
<input class="inputBox"></input>
</div>
<div class="box">
<button onclick="buttonFunction(element.inputBox)"></button>
<input class="inputBox"></input>
</div>
....
<div class="box">
<button onclick="buttonFunction(element.inputBox)"></button>
<input class="inputBox"></input>
</div>
I then want the function 'buttonFunction(element)' to look as follows:
function buttonFunction(element){
$('.element').show()
}
Where element is the specific inputbox to the specific box div.
Upvotes: 2
Views: 11450
Reputation: 19539
So long as you're using jQuery, it's much easier:
HTML:
<div class="box">
<button></button>
<input class="inputBox"></input>
</div>
<div class="box">
<button></button>
<input class="inputBox"></input>
</div>
<div class="box">
<button></button>
<input class="inputBox"></input>
</div>
JS (put this inside $(document).ready(...)
:
$('.box button').click(function(){
$(this).next('.inputBox').show();
});
Here's an example
Upvotes: 2
Reputation: 82267
There a lot of ways to approach this scenario. Usually placing a click event on the element with html is not best practice. This is a strongly typed solution which fits into your example. It will pass the element which was clicked (the button element) into the function. Then, then function as written will find the closest element with class inputBox
and issue jquery's show()
to it.
html
<button onclick="buttonFunction(this)"></button>
js
function buttonFunction(el){
$(el).parent().find('.inputBox').show();
}
Upvotes: 2