Reputation: 975
I have a foreach
to loop through and populate rows in a table. Within the table I have calls to functions and need unique ids to execute the function for each row. It works for the first row as it recognizes the ids for that row but the next row has the same id. What I am trying to do is when the field of one of the rows changes it calculates a value and enters it another field in the corresponding row.
My table is the following
<table class="table">
<tr>
<th></th>
<th class="col1">MFC DRV</th>
<th class="col1">REF Flow (slpm)</th>
<th class="col1">Calibration Flow (slpm)</th>
<th class="col1">% Diff</th>
</tr>
@foreach (var item in Model.DILlist)
{
<tr>
<td>
@Html.HiddenFor(modelItem => item.MFC_PointsID, new { htmlAttributes = new { @id = item.MFC_PointsID } })
</td>
<td>
@Html.DropDownListFor(modelItem => item.selectedDRV, item.DRVs, htmlAttributes: new { style = "Width:75px", @id = "mfc" })
</td>
<td>
@Html.EditorFor(modelItem => item.RefFlow, new { htmlAttributes = new { @id = "refFlow", style = "Width:75px", onkeyup = "myFunction(this)" } })
</td>
<td>
@Html.EditorFor(modelItem => item.CalFlow, new { htmlAttributes = new { @id = "calFlow", @disabled = "disabled", style = "Width:75px" } })
</td>
<td>
@Html.EditorFor(modelItem => item.Diff, new { htmlAttributes = new { @id = "Diff", @disabled = "disabled", @class = item.Background, style = "Width:75px" } })
</td>
</tr>
}
<tr>
</table>
and my javascript function
function myFunction(a) {
var number = a.id;
$.ajax({
type: "POST",
//Dev
url: "/CertsHelper/FlowMeterDiffCheck",
//Test and Production
//url: "/RMS_SMM/CertsHelper/FlowMeterDiffCheck",
data: { calFlow: $('#calFlow').val(), refFlow: $('#refFlow').val() },
dataType: "json",
success: function (index) {
$("#Diff").val(index);
if ($("#Diff").val() <= 2 && $("#Diff").val() >= -2) {
$("#Diff").css('background', "lightGreen");
$("#Diff").val(index);
}
else {
$("#Diff").css('background', "indianred");
$("#Diff").val(index);
}
},
error: function (error) {
alert("%Diff not working: " + error);
}
});
}
Upvotes: 0
Views: 825
Reputation: 4047
I think the issue is that you are assigning duplicate IDs to DOM elements. Give each HTML element a unique ID by concatenating the property name and the item ID.
@Html.EditorFor(modelItem => item.RefFlow,
new { htmlAttributes =
new {
@id = $"refFlow_{item.MFC_PointsID}",
style = "Width:75px",
onkeyup = "myFunction(this)"
}
})
@Html.EditorFor(modelItem => item.RefFlow,
new { htmlAttributes =
new {
@id = $"Diff_{item.MFC_PointsID}",
style = "Width:75px"
}
})
In your JavaScript function, retrieve the item ID by splitting the element ID. There are other ways to accomplish this, but for me this approach is straightforward and simple to understand.
function myFunction(a) {
var itemID = a.id.split('_')[1];
...other code...
$('#Diff_' + itemID).val();
}
Upvotes: 1