Reputation: 25
I have a table consisting of elements like this
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<button id="button"></button>
</tr>
How can i get all values of current row including selected option when press button by using jquery? I want to get: 1 'a'('a' option selected for example) 3
Upvotes: 1
Views: 54
Reputation: 1075159
If by "values" you mean the 1 and the 3 in the other two cells, you'd use closest
to find the row, then use find
or children
to access the td
s in it. Here's one way you might do it:
$("#button").on("click", function() {
// Get the row
var row = $(this).closest("tr");
// Get the cells and their contents:
row.children("td").each(function() {
var $this = $(this);
// Ignore the one with the button
if (!$this.find("button").length) {
// Does this one have the select?
var select = $this.find("select");
if (select.length) {
// Yes, use that
console.log(select.val());
} else {
// No, grab text
console.log($(this).text());
}
}
});
});
<table>
<tbody>
<tr>
<td>1</td>
<td><select>
<option>a</option>
<option>b</option>
</select>
</td>
<td>3</td>
<td>
<button id="button">I'm a button</button>
</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But refer to the API, there are lots of other ways you might access those td
s.
Note that I wrapped the button
in a td
. Your original markup is invalid, you can't have a button
as a direct child of a tr
.
Also note that if you have more than one tr
, you can't use id="button"
on all of them (probably better to use a class), but I'm guessing from the ID that that's just a placeholder you put in for the question. :-)
Upvotes: 1