Search code examples
javascriptjqueryjsoninnerhtml

get rowdata innerHTML input value of html table


I have a basic HTML table containing static value with the exception of just one cell, which contains an input field.

I am grabbing the rowdata and converting it to JSON, but the single input field is causing problems.

Without the input field, I can successfully grab all of the static values and turn them into a JSON object, as follows:

var table = document.getElementById('locationdetailsBody');
var locationjsonArr = [];
for(var i =0,row;row = table.rows[i];i++){
   var col = row.cells;
   var jsonObj = {
        currlocation : $.trim(col[0].innerHTML),
        currlocationname : $.trim(col[1].innerHTML),
        currlocationoperator : $.trim(col[2].innerHTML)
    }

  locationjsonArr.push(jsonObj);
}

The above code works, until I add .val() to the innertHTML of currlocation:

currlocation : $.trim(col[0].innerHTML.val()),

The output error is:

Uncaught TypeError: col[0].innerHTML.val is not a function

I need to be able to grab the user entered value of the input field and add it to the JSON.

How can I make this work?


Solution

  • Assuming that col[0] is a reference to the td of your table, then you can use querySelector() to retrieve the child input to retrieve its value.

    Also note that using jQuery only for $.trim() is a little wasteful. You could use the native trim() function and remove the reliance on jQuery entirely. In addition you can use map() to build the array more succinctly:

    var table = document.getElementById('locationdetailsBody');
    var locationjsonArr = Array.from(table.rows).map(row => ({
      currlocation: row.cells[0].querySelector('input').value.trim(),
      currlocationname: row.cells[1].innerHTML.trim(),
      currlocationoperator: row.cells[2].innerHTML.trim()
    }));
    
    console.log(locationjsonArr);
    <table id="locationdetailsBody">
      <tr>
        <td><input value="lorem" /></td>
        <td>ipsum</td>
        <td>dolor</td>
      </tr>
    </table>