Reputation: 463
This is my HTML table.
$(document).ready(function() {
$("button").click(function() {
$("tr").each(
$("td").each(
function() {
alert($(this).text());
}
);
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Alert the value of each list item</button>
<table>
<thead>
<th>
h1
</th>
<th>
h2
</th>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
</tr>
<tr>
<td>a2</td>
<td>b2</td>
</tr>
</tbody>
</table>
In browser it looks like this.
When I click on the button I want one alert for each table cell value.
For example from the above there are 4 cells (2 cells per row).
So I want four alerts like "a1", "b1", "a2" and "b2"
As shown above I am trying with .each
function of jquery but still no luck :(
Can someone take a look and let me know as to how do this with jquery ?
Upvotes: 1
Views: 1199
Reputation: 149
Like this?
$(document).ready(function() {
$("button").click(function() {
var ele = $("td");
$.each(ele,
function() {
alert($(this).text());
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<button>Alert the value of each list item</button>
<table>
<thead>
<th>h1</th>
<th>h2 </th>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
</tr>
<tr>
<td>a2</td>
<td>b2</td>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 22323
Don't need double loop.Single loop works for it.
$("button").click(function() {
$('tr td').each(function (index, element) {
alert($(this).text())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Alert the value of each list item</button>
<table>
<thead>
<th>
h1
</th>
<th>
h2
</th>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
</tr>
<tr>
<td>a2</td>
<td>b2</td>
</tr>
</tbody>
</table>
Upvotes: 2
Reputation: 15555
$("tr td")
selector to loop on all 4 td$('button').click(function() {
$("tr td").each(function() {
alert($(this).text());
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Alert the value of each list item</button>
<table>
<thead>
<th>
h1
</th>
<th>
h2
</th>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
</tr>
<tr>
<td>a2</td>
<td>b2</td>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 1096
You can just loop over the td
on the table like this:
$(document).ready(function() {
$("button").click(function() {
$("td").each(function() {
alert($(this).text());
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button>Alert the value of each list item</button>
<table>
<thead>
<th>
h1
</th>
<th>
h2
</th>
</thead>
<tbody>
<tr>
<td>a1</td>
<td>b1</td>
</tr>
<tr>
<td>a2</td>
<td>b2</td>
</tr>
</tbody>
</table>
Upvotes: 0