Link in Datatables table

Asked

Viewed 531 times

0

I need to create a link where I have the input name in the table using Datatables, this link should call a javascript function. The problem is that when the table is loaded it executes the script for each table row, as if all links were being clicked.

<script>
    $(function () {
        $("#insumos").dataTable({
            "bServerSide": true,
            "sAjaxSource": "/Insumo/BuscarInsumosDataTable",
            "bProcessing": true,
            "language": {
                "url": "/DataTables/Traducao"
            },
            "aoColumns":
                [
                    {
                        "sName": "InsumoId",
                        "mData": "InsumoId"
                    },
                    {
                        "sName": "Nome",
                        "mData": "Nome",
                        "render": function ( data, type, full, meta ) {
                            return '<a href="onclick=' + selecionarInsumo(data) + '">' + data + '</a>';
                        }
                    }
                ]
        });
    })

    function selecionarInsumo(nome) {
        alert("deu certo, " + nome)
    }
</script>
  • Hello. Can you make an example in jsfiddle? It’s much easier to help.

  • Tiago, ta lá, https://jsfiddle.net/Alan_Almeida/exoe3qwc/13/ I commented some lines because they are from my server’s resources, and with them it was not working.

1 answer

1


I was "simulating clicks" because filling the table was calling the function.

When you’re writing.:
return '<a href="onclick=' + selecionarInsumo(data) + '">' + data + '</a>';

The selectInsumo(data) is a javascript function and therefore will run immediately.

First embarrassment found was in the href attribute. It is started but not finished so it is necessary to change
href="
for
href="#"
If you don’t want me to lead anywhere.

When read the onclick attribute is considered javascript so to run as you want it to look like this.:

return '<a href="#" onclick="selecionarInsumo(\''+data+'\');">' + data + '</a>';

In this Return inside the onclick what is intended is text and not the function but when it is triggered the onclick will interpret javascript.



jsfiddle with the changes.:
https://jsfiddle.net/exoe3qwc/15/
For some reason the selectInsumo is not identified in jsfiddle, but I tested with a page and ran to 100%.

  • Tiago, thanks, really hadn’t thought about it, Return has to return everything as text...

  • The example posted in jsfiddle is not working and I need to do something similar, including creating a post http://answall.com/questions/151100/link-com-imagem-no-datatables-net.

  • @Adriano SUV does not work because it gives error selector, but if you create an html page and put the code that is in jsfiddle, it will work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.