Paxsentry
Paxsentry

Reputation: 193

Jquery text field updating within foreach Razor

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

Answers (4)

Kevin Coulson
Kevin Coulson

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

user4090029
user4090029

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

cohen990
cohen990

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

Dietz
Dietz

Reputation: 578

The id you specify <text id="supplierName">na</text> will be duplicated because of your foreach loop.

My suggestion is to change from using id to using class to identify the suppliernames. Then you can use jquery's .each to update all with the class name.

Upvotes: 2

Related Questions