Dynamic Search Boxes Based on Data in Column

Dynamic Search Boxes Based on Data in Column

alcor8alcor8 Posts: 5Questions: 2Answers: 0

I'd like to create search boxes at the top of my table that dynamically size themselves based on the largest data returned in the column on that page. I'm stuck trying to figure out what method I should call to get the length of the data in a column on a certain page. My code below looks at the column header but that doesn't satisfy my goal because 'Sex' can have a one column answer, but 'Address' could be over 100 characters long.

<script type="text/javascript">
    $(document).ready(function () {
        var table = $('#sortable').DataTable();

        $('#sortable thead th').each(function () {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="' + title + '" style="width : '+getTextWidth(title)+'px" />');

        table.columns().every(function () {
            var that = this;
            $('input', this.header()).on('keyup change', function () {
                if (that.search() !== this.value) {

<script type="text/javascript">
        function getTextWidth(subject) {

            inputText = subject;
            console.log(subject, ' is ', subject.length, ' long.');
            if (subject === 'Final Disposition')
                return 64;
                return (subject.length * 12);

This question has an accepted answers - jump to answer


  • kthorngrenkthorngren Posts: 13,786Questions: 25Answers: 3,242
    Answer ✓

    By default Datatables will attempt to set the column widths based on the longest string in each column. Maybe you can leverage that and just use style="width:100%" for your input. The input should fit to the column width.


  • alcor8alcor8 Posts: 5Questions: 2Answers: 0

    That worked. (I guess I was trying to overthink it).

    Thank you.

Sign In or Register to comment.