Checkboxes that activate input number on DataTable

Checkboxes that activate input number on DataTable

muhamadyuraz07muhamadyuraz07 Posts: 8Questions: 3Answers: 0

I'm creating a table of products and when i click on the checkbox it is supposed to enable an input that is in the same tr as the selected checkbox. Is there a way I can do that ?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    Are you using the Datatables Editor?

    Or are you wanting to create your own editing code?

    Kevin

  • muhamadyuraz07muhamadyuraz07 Posts: 8Questions: 3Answers: 0
    edited July 2020

    I'm not using Datatables editor.

    Plus what I'm trying to create is a table of products that when I select a checkbox in a row the input of the quantities is enabled. and then as I change the quantities of that product it sums and shows the result at some span.

    But yet I'm getting a problem, all works well on the first page but when I change the page it overrides all content and the sum.

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974

    But yet I'm getting a problem, all works well on the first page but when I change the page it overrides all content and the sum.

    The best thing to do is provide a link to your page or a test case so we can see what you are doing and offer suggestions.

    Note that when using Datatables the only rows in the DOM are the rows being displayed. If you are displaying 10 rows at a time but have 100 in the table the DOM only contains 10 rows. You will need to use Datatables APIs to update the data and to sum the data.

    Kevin

  • muhamadyuraz07muhamadyuraz07 Posts: 8Questions: 3Answers: 0
    var table = $('#example1').DataTable({
            "language": {
                "sProcessing":    "Procesando...",
                "sLengthMenu":    "Mostrar _MENU_ registos",
                "sZeroRecords":   "Não foram encontrados resultados",
                "sEmptyTable":    "Nenhum dado dísponivel nesta tabela",
                "sInfo":          "A mostrar registos de _START_ a _END_ de um total de _TOTAL_ registos",
                "sInfoEmpty":     "Mostrando registos de 0 a 0 de um total de 0 registos",
                "sInfoFiltered":  "(filtrado de um total de registos _MAX_)",
                "sInfoPostFix":   "",
                "sSearch":        "Pesquisar:",
                "sUrl":           "",
                "sInfoThousands":  ",",
                "sLoadingRecords": "A carregar...",
                "oPaginate": {
                    "sFirst":    "Primeiro",
                    "sLast":    "Último",
                    "sNext":    "Seguinte",
                    "sPrevious": "Anterior"
                },
                "oAria": {
                    "sSortAscending":  ": Ative para ordenar a coluna em ordem ascendente",
                    "sSortDescending": ": Ative para ordenar a coluna em ordem decrescente"
                }
            },
            'columnDefs': [{
                'targets': 8,
                'searchable': false,
                'orderable': false,
                'className': 'dt-body-center',
                //alocação dos checkboxes para cada <tr>
                'render': function (data, type, full, meta){
                    return '<input type="checkbox" name="produtochk" class="produtochk">';
                }
            }],
            'order': [[1, 'asc']]
        });
    
    //Ao alterar o campo de quantidade de qualquer dos produtos
        $('#example1 tbody').on("change", ".prodquantity", function () {
    
                //zerrar as variaveis para poder calcular novamente os seus valores
                valt = 0;
                arr = [];
                arrT = [];
                mts = '';
    
                //para cada checkbox da tabela
                table.$('input[type="checkbox"]').each(function(){
                    
                    //caso a checkbox estiver checkada e se o valor do campo do produto for maior que 0 ( isto impede que o array seja preenchido por campos onde a quantidade seja 0 )
                    if ($('input.produtochk').is(':checked') && $(this).closest('tr').find('.prodquantity').val() > 0) {
                        
                        //inicialização das variaveis do array
                        var id, precoCaixa, numCaixas;
                        
                        //atribuição de valores as variaveis
                        id = $(this).closest('tr').find('.id').text();
                        precoCaixa = $(this).closest('tr').find('.precoCaixa').text();
                        numCaixas = $(this).closest('tr').find('.prodquantity').val();
    
                        //calculo do valor total ( numero de caixa x preco por cada caixa )
                        valt += (numCaixas * precoCaixa);
                        
                        //atribuição das variavies ao array temporario (arr)
                        arr = {id : id, preco : precoCaixa, numCaixas : numCaixas};
    
                        //atribuição do array temporario ao array final ( arr => arrT )
                        arrT = [].concat(arrT, arr);
    
                    }else
                    {
                        //caso contrario o valor total será somado com 0 ( valt = valt + 0 )
                        valt += 0;
                    }
    
                    //transformação do valor total em uma string formatada ( mts )
                    mts = valt.toLocaleString(undefined, { minimumFractionDigits: 2 });
    
                    //exibir o valor na tala
                    $('#valpiva').html(mts + "mts");
                });
            });
    

    PS: How do i use the API and where do i find it?

  • kthorngrenkthorngren Posts: 21,443Questions: 26Answers: 4,974
    Answer ✓

    PS: How do i use the API and where do i find it?

    The API's are documented here:
    https://datatables.net/reference/api/

    I suspect part of the problem is that Datatables doesn't know about the input changes. This thread that I just answered has the same issue. See example I provided for help with this part.

    If you still need help please provide a running test case showing the issue. Thats a lot of code to study to try understanding what is happening without actually seeing it run.

    Kevin

  • muhamadyuraz07muhamadyuraz07 Posts: 8Questions: 3Answers: 0

    Thanks

This discussion has been closed.