views:

623

answers:

4

I'm generating a table of content in an ASP.NET page and I want to add client side OnClick actions to each cell (the action should be to set the value of a named TextBox control to the text in the clicked cell). If I could directly add stuff to the HTML output, I think I could do this with a single line of JavaScript in each cell.

Given that I'me not now using JQuery (and never have before), what is the simplest solution to adding this (including the time spent learning stuff)?


Edit: this seems to work

+2  A: 

If you are creating your table programmatically, using HtmlControls, you can set the onclick client attribute of the HtmlTableCell:

HtmlTableCell cell = new HtmlTableCell();
cell.Attributes.Add("onclick", "someFunction();");

However, if you're using jQuery you can do something like this:

$('td').click(function(){ // Select all the table cells on the document.
  $(this).html($('#textboxId').val()); // When clicked, change the innerHTML
});                                    // with a textbox value.
CMS
A: 

Well, your question is kind of difficult to follow, but I'll give you a few pointers.

Each control has a ClientID property. This is useful for injecting into your javascript so you know the client side id of the control.

jQuery syntax for putting text into a textbox would be like the following:

$("#" + clientId).attr("value", theValue);

and the jQuery syntax for getting text from a cell would be:

$("#" + cellId).html()
Max Schmeling
+1  A: 

You should give each cell a css class... class="contentsCell"

You can then add the following script to your head tag (along with a jquery include)

$(document).ready(function(){

$(".contentsCell").click(function(){
    CallYourFunction();
})

})

Where CallYourFunction() is you own function...

This will basically attach an

onclick=" CallYourFunction();"

to each td cell (or any other element) with the class "contentsCell"

Also, if you want to grab the text inside the cell, something like:

$(document).ready(function(){

$(".contentsCell").click(function(){
    var mytext = $(this).text();
    CallYourFunction(mytext);
});

});

Check out visualjquery.com for a great reference for jquery

Paul
+1  A: 

it depends how you're generating that table of content.

  1. If bulding up using a table control, you can add JavaScript to TableCell controls using the Attributes.Add() method.

  2. If building up with the GridView, you can add JavaScript when the RowDataBound event is raised

Russ Cam