2

...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.

1
  • Why dont you generate the div's proving also an ID? You can generate something like <div class="box" item-id="2"> And then find it with that Commented Jan 23, 2013 at 19:43

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I can't get the $('.box button').click() to trigger...weird.
@JoseCalderon Does it work in the jsfiddle I posted? It does for me. Perhaps you're using show() when you should instead be setting the elements visibility:visible?
If the button is actually a div with class="button" how does that change the event listener? $('.box .button').click()? ...I omitted this from the example for simplicity.
$('.box .button'). But if it behaves like a button, just use a button! They're very flexible.
2

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();  
}

3 Comments

.inputBox is a sibling not an ancestor.
@Madbreaks - So is the op.
@Musa - Doesn't closest search siblings? oops, I will edit that part out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.