Steve Steve - 24 days ago 6
jQuery Question

datatable search by clicking dynamically created element

I am trying to search for the band in the datatables by clicking on the band (

.search
class)

@foreach($bands as $band)
<tr>
<td class="bg-info">
<div class="search"><a href="">{{$band->name}}</a></div>
</td>
<td class="bg-info">
<b>{{$band->views}}</b>
</td>
</tr>
@endforeach


I'm searching in table with id featured. i.e.
#featured


$(document).on('click','.search', function(e) {
e.preventDefault();
var search = $(this).val();
#featured.search(search).draw();
});


But, while i click on any band i got MethodNotAllowed exception.

Answer

Your logic to achieve this isn't quite right. You need to call search() on the DataTable itself, not on a jQuery object (or a string as in your original example). Then the value of the search term is coming from the text of the a element within the .search div. Try this:

var dt = $('#yourTable').DataTable();

$(document).on('click', '.search a', function(e) {
    e.preventDefault();
    dt.search($(this).text().trim()).draw();   
}); 
Comments