tiger_groove
tiger_groove

Reputation: 1016

Javascript inserting data into cell with index and data

This seems very simple but I just can't get my head around it. I am trying to insert data I get back and replace the cell contents at the specified cell index. I am getting the data (Kevin) and index (0) back from the function call's input parameters. But I'm just not able to insert this data into the desired cell. I have tried insertCell function, but this won't replace the contents, it'll just keep appending new cells.

My console.logs report the correct index and data, I've tried inserting/replacing the content of the cell like this: td[index].innerHTML = data but this gives an error, apparently td[index] returns a object HTMLTableCellElement, so i can't do it this way.

HTML:

      <table>
            ...
            <tbody>
                <tr id="data-row-body">
                    <td></td> //need to insert here
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </tbody>
        </table>

Javscript:

function exeAPI(api, key, index, callback) {
$.ajax({
      url:"../lib/getData.php",
      type: "POST",
      data: {
          name: name,
          api: api
      },
      dataType: "text", 
      success:function(result){
          console.log(result);
        if(result){
            try {
                var jsonText = result.substr(result.indexOf('{'));
                console.log("this is the jsontext: " + jsonText);  
                var jsonObj = JSON.parse(jsonText);

                callback(jsonObj.response.result[key], index);
            } catch(e) {
                console.log(e);
                alert("Error getting rack data!");
            }
        }
      }
});

//getting back "Kevin" and "0" as parameters to insert here

function exeAPIcallback(data, index){
    var td = $('#data-table tbody td');
    var tr = $('#data-table tbody tr');
    var row = document.getElementById("data-row-body");
    console.log("This is the cell index: " + th[index].innerHTML + " ,index: " + th[index]);
    console.log("This is the cell index: " + td[index]);

    td[index].innerHTML = data; // this doesn't work

}



function popupParamChecker(){

exeAPI("getData.php", "Kevin", 0, exeAPIcallback);

$("#dialog-params").dialog({
    resizable: false,
    width: 1000,
    modal: true,
    draggable: false,
    buttons: {
        Confirm: function() {
            $( this ).dialog( "close" );
        }
    }
});
}

Is there an easier way of doing this?

Upvotes: 1

Views: 896

Answers (4)

Cybernetic
Cybernetic

Reputation: 13334

Use the following function to add content to a table cell.

function add_content_to_cell(table_selector, row_number, cell_number, content) {
    $(table_selector).find('tr')
    .eq(row_number-1).find('td').eq(cell_number-1)
    .append(content); 
    }

Simply choose the table id, the row number, the cell number and the content you wish to add.

Usage:

add_content_to_cell('#my_table', 2, 5, "I am some content")

Result:

enter image description here

Upvotes: 1

Sphinx
Sphinx

Reputation: 10729

The count of row may be many, so I added one param for your APICallback.

Below is the codes:

1. First select our all rows under the table by $('table tbody tr')

2. use .eq(index) to get the specific row

3. .find() all tds then get the specific cell to change the text.

function exeAPIcallback1(data, row, col){
  let td = $('table tbody tr').eq(row).find('td').eq(col);
  td.text(td.text()+data)
}

function exeAPIcallback2(data, row, col){
  $('table tbody tr').eq(row).find('td').eq(col).text(data);
}
table td{
  width:10px;
  height:10px;
  border:1px;
  background-color:yellow;
}

table td:nth-child(even){
  background-color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="exeAPIcallback1('test',0,0)"> Test Insert</button>
<button onclick="exeAPIcallback2('test',0,0)"> Test Replace</button>
<table>
    <tbody>
        <tr id="data-row-body">
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

Upvotes: 1

JaYdipD
JaYdipD

Reputation: 38

See if this works, with your current snippet

change

var td = $('#data-table tbody td');

to

var td = $('#data-row-body').children('td');
$(td[index]).html(data);

here, assuming that index is always within the bounds of

Upvotes: 0

user2575725
user2575725

Reputation:

With jQuery:

$('#data-row-body').find('td').eq(index).text(data); /* strips down html, if any */

OR

$('#data-row-body').find('td').eq(index).html(data); /* with html tags */

Upvotes: 0

Related Questions