Reputation: 455
I have a table in html with some code like this,
<table class="window" style="margin-top: 15px; text-align: center;">
<tr id="NavMonth">
<td id="m1" onclick="">
Jan
</td>
<td id="m2" onclick="">
Feb
</td>
<td id="m3" onclick="">
Mar
</td>
<td id="m4" onclick="">
Apr
</td>
<td id="m5" onclick="">
May
</td>
<td id="m6" onclick="">
Jun
</td>
</tr>
</table>
Now based on the onClick event, I want to store the value of the month in a variable in c#. For ex. it id "m4" is clicked, I want to store value 4 in my variable.
Any ideas will be helpful and appreciated.
Thanks.
Upvotes: 1
Views: 2325
Reputation: 37
The click event has nothing to do with c#, because it happens in the clients browser. You can react to the user event with js.
If you want to do something serverside (after the user clicked), you have to create an ajax call and send the clicked-value via a postback. jQuery...
What is the target with your serverside script containing the clicked table cell? Manipulating data in a database? Please specify....
Upvotes: 1
Reputation: 53958
You could try something like this:
var table = document.getElementById("NavMonth").
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
currentRow.onclick = function(){
alert(currentRow.getAttribute("id"));
}
}
On click of a row the value of id
of the current row will be shown on an alert box. This is the way you can get the value. The way you will use it it depends on what you want to do. Storing this value in a variable in C#
seems to me a bit odd. I assume that you may want something else. You might want to pass this value to the server and then based on this value do something else, like updating the value of a row's column in a table in your database. I can't imagine where you need this. Hence I can't provide you a concrete answer on how you will use it.
Update
How can I store this value in a c# variable or can I call a c# function in onClick event?
If you want to call a function C# supposing that you make an ajax call. You could avoid this, if you use ASP.NET web forms and not ASP.NET MVC. In this case, mybirthname suggestion is the simplest way.
Upvotes: 0
Reputation: 18127
First add asp:HiddenField in your aspx. Lets this hiddeField have ID="hidden".
After that you will use jquery to attach onClick event to the td of the table and you will set the value of the hidden field to the ID of the current td.
$(document).ready(function () {
$('.window td').on('click',function(){
var idName = this.id;
$('#hidden').val(idName);
});
});
At last in your C# code:
string text = hidden.Text;//you will remove m part of the Id and you have the number.
Be aware the code is written on the fly, probably you should check the javascript using console.log or alert functionality.
Upvotes: 0