Use jQuery to select a specific type of element in the same div as another element

I am new to jQuery and think this is the main question. I searched google and the jQuery site for information about parent and child, but I'm having problems with what I want to accomplish.

Say I have the following markup:

<div> <input type="text" value="John Doe" /> <a href="#" class="clearButton">clear</a> </div> <div> <input type="text" value="Jane Doe" /> <a href="#" class="clearButton">clear</a> </div> <div> <input type="text" value="Joe Smith" /> <a href="#" class="clearButton">clear</a> </div> 

Essentially, I want to write a little jQuery that forces each clearButton link to clear the value of its child input on click. Is this possible given my markup? Or do I need a unique identifier for each input or each div? Is it possible to get a click and then use the "this" command to select the correct input for the sibling? I compiled some of my own code using sibling, but it immediately cleared all inputs.

Any tips or links to relevant information are welcome! Thanks!

+4
source share
4 answers

If the link is always next to the input field:

 $('.clearButton').click(function() { $(this) // the clearButton .prev() // get the input field .val(''); // clear its value return false; // disable default link action (otherwise # adds to url) }); 
+8
source

Parent and Find Demo

 $(document).ready(function () { $('.clearButton').click(function () { $(this).parent().find('input').val(''); }) }); 
+5
source

You probably just need to attach .first() to your code. it should look something like this:

 $('.clearButton').click(function() { $(this).siblings().first().val(''); }); 
+4
source
 $('.clearButton').click(function () { $(this).sibling('input').val(''); }); 
+1
source

All Articles