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
jQuery parent() Method The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree.
Use closest() method to get the closest parent element matching the selector. closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.
parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.
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.
Just give them identifiers, as surely you'll need to reference them somehow elsewhere (and if your structure changes it won't break as a side-effect) - note the use of val()
, too:
<tr>
<td><input id="someName" type="checkbox"/></td>
<td><textarea id="someOther"></textarea></td>
</tr>
Then you can reference them explicitly:
$("#someName").change(function(e) {
$("#someOther").val("some value");
});
Keep it simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With