Getting value from a dynamically-generated DataTable input

左心房为你撑大大i 提交于 2019-12-11 03:32:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!