4

I have this table

<th>Example No.</th>
<th>Column 1</th>
<tr>
<td id="SampleId">3512376894</td>
<td>[email protected]</td>
</tr>

I have script that search the values by all columns. But all I want to do is search the values by first column only with td id. But I don't know how to do that. Please kindly, help me to do that? Thanks!

Here's the jsfiddle file

Here's the JScript:

function doSearch() {
        var searchText = document.getElementById('searchTerm').value;
        var targetTable = document.getElementById('dataTable');
        var targetTableColCount;
        for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
            var rowData = '';
            if (rowIndex == 0) {
                targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
                continue; //do not execute further code for header row.
            }
            for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
                rowData += targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
                if (rowIndex <= 1) {
                    document.getElementById('noresults').style.display = "block";
                }
            }
        }
    }

4 Answers 4

4

Use the snippet below to search within a given column for a certain term.

<!-- HTML -->
<table id="dataTable">
  <th>Example No.</th>
  <th>Column 1</th>
  <th>Column  2</th>
  <tr>
    <td>345678917</td>
    <td>Test 1</td>
    <td>[email protected]</td>
  </tr>
  <tr>
    <td>3512376894</td>
    <td>Test 2</td>
    <td>[email protected]</td>
  </tr>  
</table>

// JavaScript
window.onload = function(){
  var term = "3512376894";                   // term you're searching for
  var column = 0;                            // which column to search
  var pattern = new RegExp(term, 'g');       // make search more flexible 
  var table = document.getElementById('dataTable');
  var tr = table.getElementsByTagName('TR');
  for(var i = 0; i < tr.length; i++){
    var td = tr[i].getElementsByTagName('TD');
    for(var j = 0; j < td.length; j++){
      if(j == column && td[j].innerHTML == term){

      // for more flexibility use match() function and the pattern built above
      // if(j == column && td[j].innerHTML.match(pattern)){

        console.log('Found it: ' + td[j].innerHTML);
      }
    }    
  }
};

Output:

Found it: 3512376894

Working jsBin or jsFiddle or this version jsFiddle

Verions 4 | Verions 5 | Verions 6

Sign up to request clarification or add additional context in comments.

9 Comments

Why are you looping through all of the cells to get at just one of them?
@JLRishe I know I could do the same using [rows] and [cells] collection but somehow I prefer this way. However, doesn't [rows] or [cells] work the same internally ;) And, yes, your solution is just fine as well.
I wasn't trying to suggest that you should use rows and cells. You can just use td[column] to get the desired cell and nix that inner for loop.
@User014019 if(td[j].id == SampleId && td[j].innerHTML == term)
@User014019 var term = document.getElementById('searchTerm').value; check the new jsBIn
|
2

Pretty sure this is what you want to do:

function findRows(table, column, searchText) {
    var rows = table.rows,
        r = 0,
        found = false,
        anyFound = false;

    for (; r < rows.length; r += 1) {
        row = rows.item(r);
        found = (row.cells.item(column).textContent.indexOf(searchText) !== -1);
        anyFound = anyFound || found;

        row.style.display = found ? "table-row" : "none";
    }

    document.getElementById('noresults').style.display = anyFound ? "none" : "block";
}

function performSearch() {
    var searchText = document.getElementById('searchTerm').value,
        targetTable = document.getElementById('dataTable');

    findRows(targetTable, 0, searchText);
}

document.getElementById("searchTerm").onkeyup = performSearch;

working jsFiddle

2 Comments

@User014019 Please see my updated answer, and the fiddle. If you don't add a button, then the search won't work if the user pastes the text into the search box.
I don't really understand. Wouldn't that just be more annoying for the user?
1

It sounds like your problem is transversing the DOM. Here is how to loop through table rows:

var trs = document.getElementsByTagName('tr');

for(i = 0; i < trs.length; i++){
    //trs[i] is the current table row, .children[0] selects the first child
    console.log(trs[i].children[0]);
}

Then you can check the innerHtml for search terms using a regex or indexOf.

Comments

0
function processTable(tableId, searchTerm, colNumber, hideCallback, showCallBack) {

    var mySearchTerm = searchTerm || "",
        myTable = document.getElementById(tableId) || document.createElement("TABLE"),
        myRowsArray = getElements(null, "TR", myTable), //convert to array
        myRowsArrayLength = myRowsArray.length;

    var index = 0;
    for (var i = myRowsArrayLength; --i;) {
        var myTempRowElement = myRowsArray[i],
            myTempColArray = getElements(null, "TD", myTempRowElement),
            myTempCol = (myTempColArray.length > 0 ? myTempColArray[colNumber - 1] : document.createElement("TD")),
            myText = getText(myTempCol);
        if (myText === mySearchTerm) {
            showCallBack(myTempRowElement);
        }
        else {
            hideCallback(myTempRowElement);
        }
    }
};

function init() {

    var myHandler = function (e) {
        var myTermEl = document.getElementById("searchTerm"),
            myTextContent = getText(myTermEl) || myTermEl.value || "";

        processTable("dataTable", myTextContent, 1,
            function hideCallback(el) {
                el.style.display = 'none';
            },
            function showCallBack(el) {
                el.style.display = 'table-row';
            }
        );
    };

    myHandler();

    document.getElementById("searchTerm").onkeyup = myHandler;
    document.getElementById("searchTerm").onchange = myHandler;
    document.getElementById("searchTerm").onclick = myHandler;
};

(function () {
    if (this.addEventListener) {
        this.addEventListener("load", init, false)
    }
    else {
        window.onload = init;
    }
}());
var isClassMember = function (element, classname) {
    var classes = element.className;
    if (!classes) {
        return false;
    };
    if (classes == classname) {
        return true;
    };
    var whitespace = /\s+/;
    if (!whitespace.test(classes)) {
        return false;
    };
    var c = classes.split(whitespace);
    for (var i = 0; i < c.length; i++) {
        if (c[i] == classname) {
            return true;
        };
    };
    return false;
};
var getElements = function (classname, tagname, root, firstFlag, depth) {
    if (!root) {
        root = document;
    }
    else {
        if (typeof root == "string") {
            root = document.getElementById(root);
        };
    };
    if (!tagname) {
        tagname = "*";
    };
    if (depth) {
        var maxRecursion = depth;
        var all = (function getChildsElementsLevel(root, tagName, currentLevelNumber) {
            var result = [],
                currentLevelChilds = (function getLevelChilds(root, tagName) {
                    var result = [];
                    var children = root.firstChild;
                    do {
                        if (children.nodeName == tagName) {
                            result.push(children);
                        };
                    } while (children = children.nextSibling);
                    return result;
                })(root, tagName),
                currentLevelChildsLength = currentLevelChilds.length,
                nextLevelNumber = ++currentLevelNumber;

            for (var f = currentLevelChildsLength; f--;) {

                var currentEl = currentLevelChilds[f];
                result.push(currentEl);
                if (nextLevelNumber < maxRecursion) {
                    result.concat(getChildsElementsLevel(currentEl, tagName, nextLevelNumber));
                }
            }
            return result;
        })(root, tagname, 0);
    }
    else {
        var all = root.getElementsByTagName(tagname);
    }
    if (!classname) {
        return all;
    };
    var elements = [],
        allLength = all.length,
        isMyClass = isClassMember;
    if (firstFlag) {
        for (var i = 0; i < allLength; i++) {

            var element = all[i];
            if (isMyClass(element, classname)) {
                return element;
            };
        };
    }
    else {
        for (var i = allLength; i--;) {

            var element = all[i];
            if (isMyClass(element, classname)) {
                elements.push(element);
            };
        };
    }

    return elements;
};
var getText = function (n) {
    function getStrings(n, strings) {

        if (n.nodeType == 3 /* Node.TEXT_NODE */) {
            strings.push(n.data);
        }
        else {
            if (n.nodeType == 1 /* Node.ELEMENT_NODE */) {
                for (var m = n.firstChild; m != null; m = m.nextSibling) {
                    getStrings(m, strings);
                };
            };
        };
    };
    var strings = [];
    getStrings(n, strings);
    return strings.join("");
};

3 Comments

Would you mind telling us what this massive chunk of code accomplishes?
I'm a little tweaked the code. All you need to do is to find the event and start processing function processTable.
can you give us some running example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.