Get Datatables cell value that is input text field

2019-02-24 01:43发布

问题:

I'm generating a DataTable with a javascript data source. The data is returned from an ajax call to nodejs which queries SQL Server DB table and returns 2 columns, both numerical data. I'm adding 2 more columns to hold input fields, with default value of 0, for the user to enter numbers that will increase/decrease the values found in ColumnA/B.

$('#mytable').DataTable( {
    "data": data,
    "columns": [
        { "data": "ColumnA", "defaultContent": "NA" },
        { "data": "ColumnB", "defaultContent": "NA" },
        { "data": undefined, "defaultContent": '<input type="text" value="0" size="10"/>'},
        { "data": undefined, "defaultContent": '<input type="text" value="0" size="10"/>'}
    ]
});

This renders just fine and I can modify the text in the input field in the cell. There is a separate input field outside the table that the user can click to 'submit changes', which calls a javascript function that will read those input fields of the table. However, I cannot figure out how to get them. Using:

var aTable = $('#mytable').DataTable();
var colAchange = atable.cell(0, 2).data();
var colBchange = atable.cell(0, 3).data();

Both colA/Bchange vars just have the 'input type="text" ...' html text, not the value of the input field. This does make sense, but I cannot find the right way to read the value of the input field. At one time I had read in the Datatables docs that you can add 'meta' data to the row data. Do I need to do that to get an "id" on that element and query the element by that? Otherwise how do I get that input's value?

回答1:

If you just want to extract the values entered in the input boxes, you must go through jQuery or native DOM. dataTables itself is not aware of any changes made to form input fields, so trying to retrieve the values by cell().data() will never work, with or without id's / orthogonal data :

aTable.cell(0,2).nodes().to$().find('input').val()
aTable.cell(0,3).nodes().to$().find('input').val()   

Will give you the current value of the various inputs. Have replicated your above scenario 100% in this fiddle -> http://jsfiddle.net/obmghyo7/

This is basically also how the official documentation suggests a way to extract values from form inputs -> https://datatables.net/examples/api/form.html

If you want to perform filtering / searches within the table, which also includes changes made by the user in form inputs, then it is a little more tricky -> JQuery Datatables search within input and select (mine, but I dont know any better answer)