jqueryjquery-selectorsparent

Jquery Selector - How to select next column textarea


Ok,

Here's the exampe:

<table>
    <tr>
        <td>
            <type="button" id="mybutton" value="insert">
        </td>
        <td>
            <textarea>My Text</textarea>
        </td>
    </tr>
</table>

I need to change the textarea value when I click on my button. The value will come from a set variable. This code has no other IDs or classes to refer to. So I have the following

jQuery('#mybutton').click(function(){

  jQuery(this).parent().next()...????;

});

This will get me to the next column, but I don't know how to select the textarea from there.

I tried child(), another next() but no luck.


Solution

  • To select child elements in jQuery we use .children():

    jQuery('#mybutton').click(function(){
        jQuery(this).parent().next().children().val(some_variable);
    });
    

    Note that this will select all sibling elements to the textarea as well unless you add textarea as a selector in the .children() function call: .children('textarea')

    You could also use .closest() and .find():

    jQuery('#mybutton').click(function(){
        jQuery(this).closest('tr').find('textarea').val(some_variable);
    });
    

    .closest() finds the first ancestor element that matches the selector, and find, well finds the selector in the descendant elements of the root-selection.

    Some Documentation for ya: