I have a FAQs page and I want to include search functionality so people dont have to read the whole page to find what they were looking for.
jQuery("#search_submit").on("click", function () {
//var search_str = jQuery("#search_text").val();console.log(search_str);
findString('');
return false;
});
var TRange=null;
function findString (str) {
str = document.getElementById('search_text').value;//jQuery("#search_text").val();
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
var original_content = window;
strFound=original_content.find(str);
if (!strFound) {
strFound=original_content.find(str,0,1);
while (original_content.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;
}
I am using this script but I am not sure what I am doing wrong. It only searches part of the page that is before the search text input field.
Here is everything setup on jsfiddle http://jsfiddle.net/sandyrig/h86knpsq/1/
Try searching the word "stuff" or "lol" and you ll know what I mean.
edit
Also, actually all the questions in the page will be in collapsed state when the page loads so I ll customize this script so it finds text even in the collapsed answer and uncollapse it when reached while searching through the page.
Read the description on the page you linked. They've excluded the input box from the HTML of the page by putting it in an iframe. What happens in your code is that once the .find() function reaches the input field, it switches focus and restarts the search.
Try hard-coding the text you want to search to something that's not in the input field and you'll see that it works.
Working example: http://jsfiddle.net/daqb13n0/
Also, what @CurtisAutery said, a filter function would make a lot more sense. If this is the requirement from the client, then it's your job as a professional to explain to the client how they're wrong. Alternatively, they don't know what filtering is and no one asked them.
Also, now it searches for text ANYWHERE on the page, you'll want to limit your results to text inside the available questions and answers, right?
TL;DR:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With