Nithya
Nithya

Reputation: 644

jQuery datatables-how to search text in column that has html tags in a table?

My page has search box to filter particular column data.The text in the cell is displayed using html properties like <i> and <b>.

So it is a challenge for me to filter the text with <i> or <b>.

Here is html code for search box.

<form>
     <span>EnglishStaffname</span>
        <input type='text' id='EnglishStaffname_search' value=""></input> 
</form>

The script to create datatable is below:

  function createWidget(table) {
    column_data = [
    {title: "User ID", visible: false, data: "id"},
    {title: "Location", visible: true, data:"location"},
    title: "Details",
        data: "details",
        sortable: false,
        render: {
            display: function(data) {
                json = jQuery.parseJSON(data);
                s = "";

                if ("subjects" in json)
                {
                    s += "<b>subjects:</b><br />";
                    $.each(json["subjects"], function(key, value) {
                        s += " - <i>" + key + ": </i>" + value + "<br />";
                    });

                    s += "<b>hours:</b><br />";
                    $.each(json["hours"], function(key, value) {
                        s += " - <i>" + key + ": </i>" + value + "<br />";
                    });
                }
                else 
                {
                    $.each(json, function(key, value) {
                        s += "<b>" + key + ": </b>" + value + "<br />";
                    });

                }

                return s;
            }
        }
    }];}

The table displays the details column like below

1st row :

subject:

-English:Meena.K

-Maths:Ramya.v

hours:

-monday:8

2nd row:

English:Kiran.K

Maths:Ramya.v

I have tried to filter details column for English using jquery something like this:

$("EnglishStaffname_search").keyup(function() {
        try {
            item = $(this).val();
            table.column(2).search(item, true, false).draw();
        } catch(e) {

        }
    });

But the above is searching for whole cell not for only English.I have tried regex also but not getting exact match.

Can any one suggest me to get exact match irrespective of html tags?

Web page table: enter image description here

Upvotes: 1

Views: 3140

Answers (1)

abpatil
abpatil

Reputation: 916

We can do it using RegEx.
Try following code-

$(document).ready(function() {
    var table = $('#example').DataTable( {
        responsive: true
    });

    $('input[type="search"]').keyup(function(){
        var term = $(this).val();
        if(term =='') {
            regex = '';
        } else{
            regex = 'English:'+ term ;
        }   
        table.search( regex, true, false ).draw();
    })
});

Working jsfiddle.

Upvotes: 1

Related Questions