Here is my code:
var result = '';
var rows = $("#table_wf tbody tr input[type='checkbox']:checked").closest('tr');
for (var i = 0; i < rows.length; i++) {
var row = rows[i]
result += rows[i].cells[0].innerHTML;
var v = rows[i].cells.find("td input[type=text]");
if (rows[i].cells.find("input[type=text]").length) {
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<table id="table_wf">
<tbody>
<tr>
<td>A</td>
<td>Some Dummy Text</td>
<td></td>
<td><input id="chk_001" type="checkbox" selected></td>
</tr>
<tr>
<td>B</td>
<td>Some Dummy Text</td>
<td><input id="text_002" type="text" value="22"/></td>
<td><input id="chk_002" type="checkbox" selected/></td>
</tr>
</tbody>
</table>
1st column contain codes like A,B,C
2nd column contain some dummy text
3rd column might contain a input box or might not, here 1st row does not have text box, 2nd row does
4th and last column contain a checkbox
now on change of any checkbox what I want is
text from column 1 + text from column 3 text box if present
I am able to get value from first <td>
tag of row but not able to check if that row contain text box in 3rd <td>
tag and if does, retrieve it’s value
if (rows[i].cells.find("input[type=text]").length) {}
This is found on a post but it says that find rows[i].cells.find
is not a function.
Maybe .find
is not available on cells.
Anyway to accomplish this ?
value should be A (1st row), B22 (from 2nd row)
One comment suggested that rows[i].cells.find("td input[type=text]")
means that finding a td within td collection because rows[i].cells return list of td, so I changed it to
rows[i].find("td input[type=text]").length
But error is still "rows[i].find is not a function"
4
Answers
You can loop through the cells using
.eq(index)
to access the cell at a specific index within a row.Demo:
Firstly, I change
selected
tochecked
in the HTML, at least for the example. Didn’t take in count possible user input.find
is a JQuery method, not a basic dom one. By only using JQuery method likefind("td:first")
and getting it from row and not cell, it works fine:.find()
is a jQuery method that is used to search through the descendants of these elements in the DOM tree and cannot be directly applied torows[i].cells
, which is a collection of DOM elements, not jQuery objects.wrap the elements you’re working with in jQuery
Also, the
selected
attribute should bechecked
Your requirement is exactly what
.map
was designed for.Keeping with jquery one liner:
Breakdown:
.find("td").eq(0)
and returns its text.val()
will give the value of the first found|| ""
convertsundefined
to empty string.toArray()
converts the jquery .map response to a basic array.join(" ")
if you want as a single string or use the arraySnippet