问题
So, I have a dataTable that gets its data from ajax. I want two of the columns to have text inputs so that the user may edit and update the information by clicking a button in the same row. This works fine like this:
{
"render": function ( data, type, row ) {
return '<input id="nameInput" type="text" value="' + row.name + '" />';
},
"targets": 0
},
{
"render": function ( data, type, row ) {
return '<input id="hourlyRateInput" type="text" value="' + row.hourlyRate + '" />';
},
"targets": 1
},
{
"targets": 2,
"data": null,
"defaultContent": "<button>Update</button>"
},
The data is loaded into the editable text input. However, I can't find a way to extract the value from the input after this. The closest I've come is
var data = table.row( $(this).parents('tr') ).data();
which give successfully gives me the data from that row. However, the text input value never changes. If the user edits the text, data.name gives me the old data that was originally loaded into the table. Is there an efficient way to pull this data out of the text input?
回答1:
In the click event of the update button, you can get the values from the inputs like this:
var nameInput = $(this).closest('tr').find('#nameInput').val();
var hourlyRateInput = $(this).closest('tr').find('#hourlyRateInput').val();
This works by getting the parent of this
(which is your update button) and then locating the selectors by Id.
Really, the Id's should be classes because the way you're doing it produces duplicate Id's.
'<input class="nameInput" ...
And then you would get the value like this:
var nameInput = $(this).closest('tr').find('.nameInput').val();
回答2:
You should use .attr('data-name')
as .data()
give the initial value.
来源:https://stackoverflow.com/questions/28464914/getting-value-from-a-dynamically-generated-datatable-input