Search code examples
javascriptjqueryajaxcodeigniter-2codeigniter-3

How to append url last id in into search box using jquery


Im trying to append the last id of the URL into the search box of a DataTable. My URL looks like this:

Here I want to get the CL00074 value and append into the search box, like this:

[![enter image description here][1]][1]

<style>
    thead {
        .fix-search & {
            position: fixed;
            top: 10px;
            input {
                width: 250px;
            }
        }
    }
</style>

<script>  
    //this is for search 
    $(document).ready(function () {
        $('#dataTables-example').DataTable({
            responsive: true,
            "order": [[0, "desc"]],
            "columnDefs": [{
                "targets": 'no-sort',
                "orderable": false
            });
        });
</script>
<script>
    var url = window.location.href;
    var id = url.substring(url.lastIndexOf('/') + 1);
    // alert(id);

    $(document).ready(function () {
        $('#dataTables-example').append(id);
    });
</script>

If you don't understand what I'm asking, let me know guys. Any help is much appreciated

->Thank you guys fro your reply @Rory McCrossan and @Jameel Ahmed Ansari. I have find the solutions .

    var id = url.substring(url.lastIndexOf('/') + 1);
// alert(id);
$(document).ready(function () {
    $('#dataTables-example_filter input').val(id);
    $('#dataTables-example_filter input').keyup();
}); 

Solution

  • Firstly, to retrieve the required part of the URL it would be easier to split it in to an array and retrieve the final element. You can then use the fnFilter() method of the dataTable to programmatically search for that value:

    var dt = $('#dataTables-example').dataTable({
        // setup here
    });
    
    var id = window.location.href.split('/').pop();
    dt.fnFilter(id); // perform the search.