Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to select certain element type in the same Div as another element

I'm new to jQuery and have what I think is a basic question. I've searched Google and the jQuery site for information on "parent" and "children" but I'm having trouble putting into words what I want to accomplish.

Let's 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>

I essentially want to write a bit of jQuery that makes each "clearButton" link clear the value of its sibling input on click. Is this possible given my markup? Or do I need a unique identifier on each input or each div? Is it possible to receive the click, and then use the "this" command to select the correct sibling input? I put together a bit of my own code using sibling but it cleared all of the inputs at once.

Any tips or links to relevant info is greatly appreciated! Thanks!

like image 342
LearnWebCode Avatar asked Dec 01 '22 07:12

LearnWebCode


1 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)
});
like image 179
binarious Avatar answered Dec 05 '22 16:12

binarious