Reputation: 193
I am working on a simple asp.net razor display page, where I get my data trough the ViewBag. Within the data, there is a supplier id, but I want to display the supplier name. The html:
@foreach (XXX supplier in ViewBag.UnApprovedOrders)
{
<tr >
<td>
<text id="supplierName">na</text>
<script>supplierFromId("@supplier.SupplierId");</script>
</td>
</tr>
and the script:
function supplierFromId(supplierId)
{
var name;
for (var i = 1; i < list.length; i++) {
if (list[i].id == supplierId) name = list[i].name;
}
$("#supplierName").text(name);
};
The list is the suppliers list provided from elsewhere.
The question is: the function is called only once, so only the first field gets the correct name, the rest remains "na".
What is wrong?
Upvotes: 0
Views: 1500
Reputation: 548
This should work:
@foreach (XXX supplier in ViewBag.UnApprovedOrders)
{
<tr >
<td>
<text class="supplierName">@supplier.SupplierId</text>
</td>
</tr>
}
<script>
$(document).ready(function() {
$('.supplierName').each(function() {
var supplierId = $(this).text();
var name = '';
for (var i = 0; i < list.length; i++) {
if (list[i].id == supplierId) name = list[i].name;
}
$(this).text(name)
});
});
</script>
Upvotes: 1
Reputation:
<text id="supplierName">na</text>
You are creating many tag within id supplierName
, but only the first tag can be applied.
To fix this, try to convert id
to class
, like this:
<text class="supplierName">na</text>
<script>
$(".supplierName").each(function() {
// do something...
});
</script>
Upvotes: 2
Reputation: 83
An ID is specifically identifying a single element. Using a class should make this work. Classes are designed to be used on multiple elements and will allow you to update all of your elements
Upvotes: 2