Reputation: 35
I'm inside of a .each loop trying to access a specific table cell (td) in a set of rows. Each row has three cells with the classes of Id, Name, and Practice.
Code:
@foreach (var client in ViewBag.ClientList.getDatabase())
{
<tr class="ClientRow">
<td class="Id">@client.Id</td>
<td class="Name">@client.getClientName</td>
<td class="Practice">@client.getPracticeID</td>
</tr>
}
//Some time later when trying to access from the foreach
$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").val();
var ID = $(this).children(".Practice").val();
The Name and ID vars always seem to return empty strings.
Upvotes: 0
Views: 319
Reputation: 594
val() is used for inputs, in your case you have to use:
$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").text();
var ID = $(this).children(".Practice").text();
Upvotes: 0
Reputation: 53198
.val()
is used to retrieve the value
attribute (it's a shortcut for .attr('value')
), and this can only be used on elements that support such a thing (for example <input />
, <select>
or <textarea>
.
Here's what the jQuery Docs say about the val()
function:
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case ofselect
elements, it returnsnull
when no option is selected and an array containing the value of each selected option when there is at least one and it is possible to select more because themultiple
attribute is present.
To get the innerHTML
or the text content of an element, you should use .text()
or .html()
.
For example:
$(".ClientRow").each(function (index) {
var Name = $(this).children(".Name").text();
var ID = $(this).children(".Practice").text();
.text()
returns the actual text of the element (without any HTML).
.html()
will return the innerHTML
of the element.
Upvotes: 5