Search code examples
javascriptjqueryhtmlstringtraversal

Get the parent row and find an element in JQuery


I have a checkbox in a column of an html table. When I check or uncheck it I want some text to be displayed/removed from a text area in the next column of the same row.
I did the following:

$(this).parent().parent().find('textarea').text = 'some text' 

and also

$(this).parent().parent().find('textarea').val = 'some text' 

but it does not work.

The html is like:

<tr>
    <td>
        <input type="checkbox" />
    </td>
    <td>
        <textarea>
    </td>
</tr>

I want to get the textarea of the same tr of the checkbox I check

UPDATE

I found that I should use .val("some text") but now the function is called only if I click the checkbox in the first row. Not for the rest


Solution

  • The issue is with how you are trying to set the value not how you are finding the element

    try this

    $(this).closest('tr').find('textarea').val("some text");
    

    See here for more info .val()

    UPDATE

    an element ID has to be unique so you can't reuse the same one. Give all your checkboxes unique id's i.e "chkOne", "chkTwo" etc. Then use a class on all the checkboxes you wish to run this functionality from. i.e class="chkSelection". Then change your jQuery to look like this

    $('.chkSelection').change(function() {
       if($(this).is(':checked')){
          $(this).closest('tr').find('textarea:first').text('Some text here');
       }
    });
    

    This way all your checkboxes with a class of "chkSelection" when changed will run the functionality to find the next textarea and set the text.