tags:

views:

34

answers:

2

Hello, i have a table and i want the data from the cells to be printed onto a input field when i click the a specific table cell using the "onclick" command. i was thinking about getdocumentbyid or something like that

greet

A: 

How about setting a unique ID for each cell, then calling document.getElementById("<id>").innerHTML to get the contents?

Or, better yet, if the onClick event is for the same element you want to get the contents of, you won't need an ID; you should be able to just use this.innerHTML.

lc
@mannetje88 What happens instead?
lc
A: 

The easiest way to do this is have a single event handler on the table or table row to handle the onclicks for you, rather than applying an onclick handler to each cell. The onclick event will bubble from the TD elements up to the table element for which the handler will fire. This is called delegation.

An example:

// Get a handle to the input box
var myInput = document.getElementById("myInput");

// Set up the onclick event for the table
document.getElementById("mytable").onclick = function (evt) {
    // window.event for IE, evt argument for others
    var evt = evt || window.event;
    // Get the element the event originated from
    var el  = evt.target || evt.srcElement;

    // If the element's tagName is <TD>, set the text of the input
    if (el.tagName == "TD")
        // innerText for IE, textContent for others
        myInput.value = "textContent" in el ? el.textContent : el.innerText;
}

If you just want it for a specific row, set the onclick event for that row instead.

Andy E