简体   繁体   中英

jQuery dataTables and selecting a row

I am trying to get a jQuery dataTable to behave in such a way that a user can select a row and then click a button (located elsewhere on the page, but not on the table or in it) and have a JS alert pop up.

Here is my dataTable:

$("#my-datatable").dataTable( {
    "bProcessing" : true,
    // Commenting out next line
    //"sDom" : 't',
    "sAjaxSource" : "some/url/on/my/server",
    "sAjaxDataProp" : "",
    "bDestroy" : true,
    "fnServerData" : function(sSource, aoData, fnCallback) {
        aoData.push({
            "name" : "asking",
            "value" : "yes"
        });

        request = $.ajax({
            "dataType" : "json",
            "type" : "GET",
            "url" : sSource,
            "data" : aoData,
            "success" : fnCallback
        });
    },

    "aoColumns" : [
        {
            "mDataProp" : "name"
        },
        {
            "mDataProp" : "expr"
        },
        {
            "mDataProp" : "seq"
        }
    ]
});

Here is my button:

<div id="bam-btn-div">
    <input type="button" id="bam-btn" value="BAM!" onclick="bam();"/>
</div>

When the user selects a row in the dataTable, and then clicks the button, I want the following function called:

function bam() {
    alert("Deleting the selected row");

    // Delete the selected row in the dataTable
}

Finally, the HTML table that the jQuery dataTable is attempting to populate:

<div id="datatable-div">
    <table id="optconfig-datatable">
        <thead>
            <tr>
                <th>Name</th>
                <th>Expression</th>
                <th>Sequence</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

I tried to follow the example here but couldn't get anything to work. Can anybody spot what configurations I need to add (to the dataTable and/or otherwise)? Thanks in advance!

You are using jQuery, you might as well stay on track.

$('#bam-btn').on('click', function(){
    alert("BAM!");
});

On a side note, ID's must be unique, but I'm sure you know that, so make sure you're not trying to re-use the same ID over and over.

Moreover, if this element is added into the DOM after .ready() execution, you'll need to attach the event handler to a static parent element so it may delegate the click event properly.

$(document).on('click', '#bam-btn', function(){
    alert("BAM");
});

I'll leave the above in place, I don't like to delete entire portions of my answer as you never know who may find it helpful in the future

First, we need to create a variable that's available to all scopes of all functions. This way, we can reference the variable to get a hold of the element we want to remove.

We should place this variable outside of the document ready function

var theRow = '';
$(document).ready(function(){ 
    //existing code here
});

Now that we have a 'global scope' variable prepared, we can modify it and access it anytime.

var theRow = '';
$(document).ready(function(){ 
    $('tr').click(function(){
        //we need to store a unique piece of information about this row.
        //Without much to go on, I'm going to rely on the index.
        theRow = $(this).index();
    });

    $('#bam-btn').click(function(){
       $('tr').eq(theRow).remove(); 
    });
});​

And here is your decent working jsFiddle as an example

For future users, and anyone else whom may find this useful

The :eq() selector provided by jQuery cannot leverage .querySelectorAll() to gain a decently large performance boost. Because of this, and for the time being, you should always use .eq() over :eq() .

Please check that your:

function bam() {
    alert("BAM!");
}

Is not in this statement:

$(document).ready(function() {
    // STATEMENT
});

If your function is in the $(document).ready() , that means it's available only in that scope, in that particular function() .

Move your code above or below the $(document).ready() statement, and your onclick event handler in your button will be able to find it and invoke it.

To delete a specific element from your data-table, try with this JavaScript:

$(document).ready(function() {
    var oTable = $("#my-datatable").dataTable( {
        "bProcessing" : true,
        // Commenting out next line
        //"sDom" : 't',
        "sAjaxSource" : "some/url/on/my/server",
        "sAjaxDataProp" : "",
        "bDestroy" : true,
        "fnServerData" : function(sSource, aoData, fnCallback) {
            aoData.push({
                "name" : "asking",
                "value" : "yes"
            });

            request = $.ajax({
                "dataType" : "json",
                "type" : "GET",
                "url" : sSource,
                "data" : aoData,
                "success" : fnCallback
            });
        },

        "aoColumns" : [
            {
                "mDataProp" : "name"
            },
            {
                "mDataProp" : "expr"
            },
            {
                "mDataProp" : "seq"
            }
        ]
    });$("#my-datatable").dataTable( {
        "bProcessing" : true,
        // Commenting out next line
        //"sDom" : 't',
        "sAjaxSource" : "some/url/on/my/server",
        "sAjaxDataProp" : "",
        "bDestroy" : true,
        "fnServerData" : function(sSource, aoData, fnCallback) {
            aoData.push({
                "name" : "asking",
                "value" : "yes"
            });

            request = $.ajax({
                "dataType" : "json",
                "type" : "GET",
                "url" : sSource,
                "data" : aoData,
                "success" : fnCallback
            });
        },

        "aoColumns" : [
            {
                "mDataProp" : "name"
            },
            {
                "mDataProp" : "expr"
            },
            {
                "mDataProp" : "seq"
            }
        ]
    });

    $('button#bam-btn').on('click', function() {
        var anSelected = fnGetSelected( oTable );
        oTable.fnDeleteRow( anSelected[0] );
    } );
});

I had a similar problem with a table with dynamic data load. Every time I was adding contents, the old nodes disappear, losing the events linked. I solved the problem invoking a function after the data load:

    function insertevents(table_id){
        var oTable = jQuery('#'+tableid).dataTable( {"bRetrieve": true });
        oTable.$('tr').click(function(){
            jQuery(this).toggleClass('row_selected');
        } );
        // Extra code here
    }

It's important to add the "bRetrieve" parameter because the table was previously initialized.

Also, I've improved the functionality controlling keyboard events for accessibility:

        oTable.$('tr').keyup( function(event) {
            if (event.which == 13 || event.which == 32) {
                event.preventDefault();
                jQuery(this).toggleClass('row_selected');
            }       
        } ); 
        oTable.$('tr').keydown( function(event) {
            if (event.which == 13 || event.which == 32) {
                event.preventDefault(); // Desactivamos este efecto
            }
        });

This bunch of lines should replace the comment line of the first example. Now the table can be used from the keyboard, selecting with intro or space key. Remember to add a tabindex=0 to the elements inserted in the table, so we can navigate with the tab key.

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