I'm using ASP MVC4 with razor and I'm stuck to return some infos from my view to my controller in a list with the below elements... I use the TextBox to be able to run my js function... I use the following (updatesum()) javascript to dynamically calculate in the field the sum of the archer's score in my view:
<td>
@Html.TextBox("suma["+@i+"]", Model[i].ArchScore1, new{ @onchange = "updatesum()"})
@Html.ValidationMessageFor(x => x[i].ArchScore1)
</td>
<td>
@Html.TextBox("sumb["+@i+"]", Model[i].ArchScore2, new { @onchange = "updatesum()" })
@Html.ValidationMessageFor(x => x[i].ArchScore2)
</td>
<td>
@Html.TextBox("sumt["+@i+"]", Model[i].ArchTot`enter code here`alScore, new { @onchange = "updatesum()" })
@Html.TextBoxFor(x=>x[i].ArchTotalScore)
@Html.ValidationMessageFor(x => x[i].ArchTotalScore)
</td>
<script type="text/javascript">
function updatesum() {
for (i = 0; i < 15; i++) {
var sua = "suma_" + i + "_";
var sub = "sumb_" + i + "_";
var sut = "sumt_" + i + "_";
suma = document.getElementById(sua).value;
sumb = document.getElementById(sub).value;
sum = (suma - 0) + (sumb - 0);
document.getElementById(sut).value = sum;
}
}
</script>
Do you know if it is feasible to add the result of this javascript function into the TextBoxFor?
Here is the code of my after the modifications suggested:
<td>
@Html.TextBoxFor(m => m[i].ArchScore1, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchScore1)
</td>
<td>>
@Html.TextBoxFor(m => m[i].ArchScore2, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchScore2)
</td>
<td>
@Html.TextBoxFor(m => m[i].ArchTotalScore, new{ @class = "score" })
@Html.ValidationMessageFor(x => x[i].ArchTotalScore
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Save" />
</p>
}
<script type='text/javascript'>
$('.score').change(function () {
var inputs = $(this).closest('tr').find('input');
inputs.eq(2).val(new Number(inputs.eq(0).val()) + new Number(inputs.eq(1).val()));
});
</script>
The 3rd textbox is still not populated.
@Html.TextBox("suma["+@i+"]", Model[i].ArchScore1) should be@Html.TextBoxFor(m => m[i].ArchScore1)