Reputation: 1738
I am new to MVC and now I am trying display a list of items each one composed of a Name
and a checkbox bound to a property (Selected
) in the model.
I want to handle certain validations when the user clicks the checkbox so my approach was to set the onclick event as shown below.
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.CheckBoxFor(modelItem => item.Selected,
new {@onclick="alert($(this).val());"})
</td>
</tr>
}
The problem is that $(this)
does not refer to the checkbox as I expected and I can't see the chekcked property (as a fact I have not been able to determine what $(this)
points to)
I can't get the DOM element by id because razor does not set the id and can't select it by class because the list contains several checkboxes all of them of the same class.
I have some ideas on how to solve this but I am sure there must be a strightforward way to do it, so...
How do I retrieve the checked value of the checkbox?
Upvotes: 0
Views: 1566
Reputation: 888187
Inside an inline event handler, this
refers to the DOM element.
this.checked
will tell you whether it's checked or not.
$(this)
is a jQuery object containing this
; jQuery objects do not have a checked
property.
.val()
will return the value of the value
attribute.
Upvotes: 1