Search code examples
javascriptcell

Obtaining the clicked value from a table cell in an text input


I have a table with 6 COLS and 12 ROWS. In the first column is a filed with dimensions (4 ml) and in the other 5 columns are the prices with are different one from another.

What I like to do is when I click on a cell from the table to autocomplete below 2 inputs 1 with dimension and another with the price from that cell.

I've manage to do the first part but the second one I don't know how to do. Please have a look at my code below:

<script>
(function () {
if (window.addEventListener) {
    window.addEventListener('load', run, false);
} else if (window.attachEvent) {
    window.attachEvent('onclick', run);
}

function run() {
    var t = document.getElementById('myTable');
    t.onclick = function (event) {
        event = event || window.event; //IE8
        var target = event.target || event.srcElement;
        while (target && target.nodeName != 'TR') { // find TR
            target = target.parentElement;
        }
        //if (!target) { return; } //tr should be always found
        var cells = target.cells; //cell collection - https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement
        var cells = target.getElementsByTagName('td'); //alternative

        var f1 = document.getElementById('Inaltime / Dimensiune');
        var f2 = document.getElementById('Ø');
        f1.value = cells[0].innerHTML;
        f2.value = cells[1].innerHTML, cells[2].innerHTML;
        //console.log(target.nodeName, event);
    };
}

})();


Solution

  • Not sure if your above code is working till f1.value, but if it does and if you are checking for only f2.value then this is what you have to do

     f2.value = cells[1].innerHTML + ',' + cells[2].innerHTML;