daniella
daniella

Reputation: 401

search page function for internet explorer

I need to put a search page function in the site that I'm working on. I found one online and it works great in Firefox and Chrome but not at all in IE. I think the fact that I didn't write this code is making it particularly hard to debug. Any help or guidance is appreciated!

HTML

<form id="f1" name="f1" action="javascript:void(0)" onsubmit="searchpage()" >
<input id="t1" type="text" name="t1" />
<input id="button" type="submit" value="FIND" name="b1" onclick="searchpage()" />
</form>

JAVASCRIPT

function searchpage() {
    if (document.getElementById("t1").value != null && this.document.getElementById("t1").value != '') parent.findString(document.getElementById("t1").value);
    return false;
}
var TRange = null;

function findString(str) {
    if (parseInt(navigator.appVersion) < 4) return;
    var strFound;
    if (window.find) {
        // CODE FOR BROWSERS THAT SUPPORT window.find
        strFound = self.find(str);
        if (!strFound) {
            strFound = self.find(str, 0, 1);
            while (self.find(str, 0, 1)) continue;
        }
    }
    else if (navigator.appName.indexOf("Microsoft") != -1) {
        // EXPLORER-SPECIFIC CODE
        if (TRange != null) {
            TRange.collapse(false);
            strFound = TRange.findText(str);
            if (strFound) TRange.select();
        }
        if (TRange == null || strFound == 0) {
            TRange = self.document.body.createTextRange();
            strFound = TRange.findText(str);
            if (strFound) TRange.select();
        }
    }
    else if (navigator.appName == "Opera") {
        alert("Opera browsers not supported, sorry...")
        return;
    }
    if (!strFound) alert("String '" + str + "' not found!") return;
}​

it is also important to note that while this works in Firefox and Chrome, the "string not found!" alert box doesn't work

Upvotes: 0

Views: 4411

Answers (1)

Tim Down
Tim Down

Reputation: 324717

Here's a version dapted from another answer of mine.

Demo: http://jsfiddle.net/MRp2G/5/

Code:

function doSearch(text) {
    var sel;
    if (window.find && window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            sel.collapseToEnd();
        }
        window.find(text);
    } else if (document.selection && document.body.createTextRange) {
        sel = document.selection;
        var textRange;
        if (sel.type == "Text") {
            textRange = sel.createRange();
            textRange.collapse(false);
        } else {
            textRange = document.body.createTextRange();
            textRange.collapse(true);
        }
        if (textRange.findText(text)) {
            textRange.select();
        }
    }
}

Upvotes: 1

Related Questions