Is there way to set razor @HTML.Hidden control value within a JavaScript code block?
<tbody>
@Html.Hidden("customerID")
@if (Model != null)
{
var customers = Model.Customers.ToList();
for (var i = 0; i < customers.Count; i++)
{
<tr class="gradeX">
<td>
<a href="#"><span onclick="GetCustomerID()">@customers[i].CustomerId.ToString()</span></a>
</td>
<td>
<a href="#">@customers[i].Name</a>
</td>
</tr>
}
}
</tbody>
and my JavaScript block is
<script type="text/javascript">
var globleCustomerId = null;
function GetCustomerID() {
globleCustomerId = $('#customerID').val();
//globleCustomerId value should be set to @Html.Hidden()
}
</script>
Within this JavaScript block I need to set globleCustomerId value to @Html.Hidden(“customerID”).
How to get that value?
You could use the
.val()method:There are 2 overloads: the one that doesn’t take any arguments and which allows you to read the value (and which is what you have shown in your question) and one that takes an argument and sets the value (the one I have shown in my answer).
UPDATE:
Apparently you are trying to put the value of the customer id that was clicked upon in the hidden field. In this case you could simply give a class to your span element:
and then simply subscribe to the click event of this element: