简体   繁体   中英

jQuery Datatables - Can't get input value from hidden pages

I have this table in my HTML:

<table>
    <thead>
        <tr>
            <th>Id</th>
            <th>Actual weight</th>
            <th>New weight</th>
        </tr>      
    </thead>

    <tbody>
        <tr>
            <td>1</td>
            <td>10</td>
            <td><input data-id="{{ object.id }}" type="number" name="input_new_weight" /></td>
        </tr>

        <tr>
            <td>1</td>
            <td>20</td>
            <td><input data-id="{{ object.id }}" type="number" name="input_new_weight" /></td>
        </tr>

        <!-- multiply by 10 the number of trs -->
    </tbody>
</table>

And I have this code in my javascript to get the input values:

var new_weights = []
$("input[name='input_new_weight']").each(function(index, element){

    if( $(this).val() != "" ){
        var object_new_weight ={
            id: $(this).data('id'),
            new_weight: $(this).val()
        }
        new_weights.push(object_new_weight);
    }

});
console.log(new_weights);

I'm using jQuery DataTables plugin to generate the tables and have the possibili ty to filter, paginate, ordenate and etc.

In some tables I have more than 10 entries, so the paginations works here. In the example above, it will be 2 pages: 1 and 2.

When my javascript code is executed, it does only gets the inputs values from the visible table page. The inputs from the hidden pages are not get!

Let's suppose that in page 1 I put the new weight values as 35, 75 and 80 and in the page 2 I put 40, 54, 97. When my javascript code runs, it does just get the values from the visible page.

Please, can someone tell me why this is happening?

It's really straightforward you know datatable generates table on the fly so when you are on page 1, inputs corresponding to page 2 (40, 54, 97) aren't there at all on the page.

So I am guessing you have put your this code out in the global

$("input[name='input_new_weight']").each(function(index, element){
    //stuff
});

This runs only one time; on initial loading of your page when inputs from only page 1 are there, what you rather need is to be able to run your code every-time datatable re-renders.There's a hook that you may use page.dt

Put this after the code where you initialize datatable

$('#yourtable').on('page.dt', function(){

    $("input[name='input_new_weight']").each(function(index, element){
        //stuff
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM