I’m creating table like this:
<table>
<tr>
<th>Column</th>
</tr>
@foreach (var item in someList)
{
foreach (var item1 in item)
{
<tr>
<td onclick="myMethod();">@item1.name</td>
</tr>
}
}
</table>
And here is the method which is called when the row is selected:
<script type="text/javascript" language="javascript">
function myMethod() {
var clickedCell = $(this);
alert(clickedCell.text());
}
</script>
But it’s not working! How can I get the text from the row/cell which is selected/clicked on?
I also tried:
<script type="text/javascript" language="javascript">
function myMethod() {
alert($(this).html());
}
</script>
and it’s giving me null althought the table is full.
I’m inferring from this line that you’re using jQuery:
If that’s the case, let’s take a step back for a moment and separate your JavaScript from your HTML. Instead of this:
which has in-line JavaScript (which is generally frowned upon), try something like this:
Now it’s just markup, which is a bit cleaner. Next you need to attach click events to your rendered cells:
Now
thisrefers to the element to which jQuery is binding the click event, so it can be easily referenced in the code, as opposed to having to pass a self-reference from the click event being bound within the HTML (which is another approach, but continues down the road of mixing markup with code).