DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Javascript/XML Based Search

09.26.2006
| 85421 views |
  • submit to reddit
        // Use javascript to search an XML based index.
// Provides simple site search where no server-side
// alternatives are available (for example: on a CD ROM)

// The sample XML:
<?xml version="1.0" encoding="utf-8"?>
<searchable_index>
	<item>John</item>
	<item>Paul</item>
	<item>George</item>
	<item>Ringo</item>
</searchable_index>

// The javascript:
window.onload = loadIndex;

function loadIndex() { // load indexfile
// most current browsers support document.implementation
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.load("index.xml");
	}
// MSIE uses ActiveX
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.load("index.xml");
	}
}


function searchIndex() { // search the index (duh!)
	if (!xmlDoc) {
		loadIndex();
	}
	// get the search term from a form field with id 'searchme'

	var searchterm = document.getElementById("searchme").value;
	var allitems = xmlDoc.getElementsByTagName("item");
	results = new Array;
	if (searchterm.length < 3) {
		alert("Enter at least three characters");
	} else {
		for (var i=0;i<allitems.length;i++) {
// see if the XML entry matches the search term,
// and (if so) store it in an array
			var name = allitems[i].lastChild.nodeValue;
			var exp = new RegExp(searchterm,"i");
			if ( name.match(exp) != null) {
				results.push(allitems[i]);
			}
		}
// send the results to another function that displays them to the user
	showResults(results, searchterm);
	}
}


// The following is just an example of how you
// could handle the search results
function showResults(results, searchterm) {

	if (results.length > 0) {
// if there are any results, put them in a list inside the "resultshere" div
		var resultshere = document.getElementById("resultshere");
		var header = document.createElement("h5");
		var list = document.createElement("ul");
		var searchedfor = document.createTextNode("You've searched for "+searchterm);
		resultshere.appendChild(header);
		header.appendChild(searchedfor);
		resultshere.appendChild(list);
		for (var i=0;i<results.length;i++) {
			var listitem = document.createElement("li");
			var item = document.createTextNode(results[i].lastChild.nodeValue);
			list.appendChild(listitem);
			listitem.appendChild(item);
		}
	} else {
// else tell the user no matches were found
		var resultshere = document.getElementById("resultshere");
		var para = document.createElement("p");
		var notfound = document.createTextNode("Sorry, I couldn't find anything like "+searchterm +"!");
		resultshere.appendChild(para);
		para.appendChild(notfound);
	}
}

// Here's some s(a|i)mple HTML that should work with the code above:

<html>
<head>
<script type="text/javascript" src="searchindex.js"></script>
</head>
<body>
<form action="">
<input type="text" id="searchme" />
<input type="submit" onclick="searchIndex(); return false;" />
</form>
<div id="resultshere">
</div>
</body>
</html>

    

Comments

Eliza Kaye replied on Wed, 2013/03/06 - 6:56pm

Thank you I have the name being found and the name coming through, but because of the way the code was displayed for writing the rest of the relevant info belonging to that person I could not understand it.

 

Is there some way you could please put it in an example and allow us to copy the full code?

 

Thanks

Carla Brian replied on Thu, 2012/07/26 - 6:31pm

I have to read more about java script. I am new to this one and I need to learn on this. - Mercy Ministries

Snippets Manager replied on Wed, 2010/03/31 - 5:27am

I like the code above, but I have a slightly different requirement. Loading the XML, then using a form with searchterm of "customer". The code is very similar, but each entry in the XML is different. using Some customer 1. When I search for something that may be listed in the XML, then I want an alert box that will say ("+Searchterm+ is found" or ("+Result+ is found") I do not want it to display a new page with the result in, only an alert that will say no it's not found, or yes it is found. 2. Another thing is a custom alert, or popup. If possible a red cross instead of a triangle-with-exclamation when not found, and a green tick when found, with the appropriate text and button of course. Can someone help? Here's what I'm trying to use: // JavaScript Document window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("cust.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("cust.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'circuit' var searchterm = document.getElementById("customer").value; var allitems = xmlDoc.getElementsByTagName("customer"); results = new Array; if (searchterm.length < 9) { alert("Enter the whole name"); } else { for (var i=0;i 0) { for (var i=0;i

Snippets Manager replied on Sat, 2010/05/08 - 9:00am

Thanks. I will take a look at it. By the way, thanks for sharing your hard work.

Snippets Manager replied on Mon, 2010/05/10 - 4:01pm

@mike248x and others... I've re-wrote the script above using jQuery framework. Here is a discription and full code Download it at: http://www.blencorp.com/blog/2010/04/jsearch-simple-jqueryxml-based-search/

Snippets Manager replied on Sun, 2010/09/12 - 9:23am

i finally found a way to have this work with chrome. see: http://code.google.com/p/chromium/issues/detail?id=988#c9 still looking for a fix for ie.

Snippets Manager replied on Sun, 2010/09/12 - 9:23am

this, the original post & mapmaker's, doesn't seem to work in chrome and ie8 (currently installed). any idea why? any workaround?

Snippets Manager replied on Thu, 2011/09/01 - 4:41am

Hello, if somebody coul help me please. How i can make the code from "search.html", to search in xml, from multiple criteria. My XML file is something like this: ALTERNATOR Now is searching just if i enter the name, if i enter that id number, its do not find nothing. Thank you wery much for help!

Snippets Manager replied on Sat, 2010/12/18 - 1:28am

very good all the improvements but someone could add style to the results with CSS, please comment the solution.

Snippets Manager replied on Mon, 2012/04/30 - 12:05pm

Please help mir.Ich am a beginner. None of the above-written code does not work for me. They always show "no results". So find they do not. What am I doing wrong?

Snippets Manager replied on Fri, 2011/03/04 - 4:18am

Sorry, I was wrong... I have to search using "ID" and display all "User" element... This is the XML 95 29 Robert Hassen Paris usr93 Documents\Abcd.pdf Could you help me?

Snippets Manager replied on Fri, 2011/03/04 - 4:18am

Can you tell me how to display all child nodes for each result? Thanks in advance

Snippets Manager replied on Wed, 2010/03/31 - 5:27am

Hi I am still trying to get a popup that will indicate if a specific value is found in a xml file. Getting it to tell me it's not in the file is easy enough, but I just can't get it to do it the other way round. I don't want to open a new page that displays results. So if anyone has any ideas. Please help. // JavaScript Document function getType() { for (var i=0; i < 2; i++) { if (document.frmSPC.criteria[i].checked) { var rad_val = document.frmSPC.criteria[i].value; } } return rad_val; } window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("/search/fnb.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("/search/fnb.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'spc' var searchterm = document.getElementById("spcsearch").value; var allitems = xmlDoc.getElementsByTagName("item"); var results = new Array; if (searchterm.length < 9) { alert("Enter the whole circuit number"); } else { for (var i=0;i 0) { for (var i=0;i Here's the code for the html

SPC Search Form
Number:

Snippets Manager replied on Fri, 2011/10/07 - 2:32pm

This original script is no longer working in Internet Explorer 9 or Google Chrome, does anyone have a new solution to this issue? (it had previously worked in all 3, still works fine in Firefox) Thanks in advance for any help.

Snippets Manager replied on Wed, 2010/07/21 - 6:36am

Hi, This is exactly what I was looking for! Tks a lot! Is it possible to search information of a XML based on partial information that is not on the beginning of the tag? Exemple: I'm looking for a name that contains "ark" in the name... it should bring me "Clark", "Mark", Etc... Thanks.

Snippets Manager replied on Sat, 2010/05/08 - 9:00am

Hey guys, I'm very new to this. Can someone please tell me how to hyperlink the results using the first example xml and the Javascript on the top of the page? Any help will be sincerely appreciated. Thanks in advance.

Snippets Manager replied on Mon, 2011/12/12 - 3:49pm

Scrub that guys... I've added after if (results.length >0){ mywin.window.open('',target="balnk", 'height=xx,width=xx,scrollbars=no,menu=no,resizable=no'); in fron of each document.write add mywin. so.. mywin.document.write('all your stuff') .. .. mywin.document.close(); mywin.focus(); This will display your results in a new blank page which if you do some work adding div tags etc you can customize with all your results in. Hope this helps someone.

Snippets Manager replied on Mon, 2011/12/12 - 3:49pm

Hi guys Great post, I've created a search page which returns search results from my xml using all the advise above. Cheers However, using 'document.write' creates a blank 'white'document, and if I use mapmakers version(cheers for that) the document isn't erased a new search will just add more data to that document. I need to return the search results in the current web-browser or preserve the current web browser format. I've been trying to use W3schools 'http://www.w3schools.com/xml/xml_http.asp' XMLHttprequest but this requires asp and i'm trying not to use active server pages. Any thoughts? Many thanks.

Snippets Manager replied on Tue, 2009/09/01 - 6:21pm

Any ideas on how to make the search results links? i.e. my search is for documents so I want to be able to have links on the results page e.g. John

Snippets Manager replied on Wed, 2009/08/26 - 2:27pm

I have modified this to include radio buttons so that you can search by attribute and manipulated the code for the same... Something I wanted to do. Right now it simply displays the same as the original code. Search function getType() { for (var i=0; i < 4; i++) { if (document.frmMain.criteria[i].checked) { var rad_val = document.frmMain.criteria[i].value; } } return rad_val; } window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("index.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("index.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'searchme' var searchterm = document.getElementById("searchme").value; var searchtype = getType(); var allitems = xmlDoc.getElementsByTagName("item"); results = new Array; if (searchterm.length < 3) { alert("Enter at least three characters"); } else { // see if the XML entry matches the search term, // and (if so) store it in an array \ for (var i=0;i 0) { // if there are any results, write them to a table document.write('New SearchYou searched for '+searchterm+'

'); document.write(''); document.write(''); for(var i=0; i'); document.write(''); document.write(''); document.write(''); document.write(''); document.write(''); } document.write('
NAMEAGEHEIGHTWEIGHT
' + results[i].getAttribute("name") + '' + results[i].getAttribute("age") + '' + results[i].getAttribute("height") + '' + results[i].getAttribute("weight") + '
'); document.close(); } else { // else tell the user no matches were found var notfound = alert('No results found for '+searchterm+'!'); } } Search:  

Name             Age                  Height               Weight

  

Hope this helps anyone who wanted to achieve the same effect.

Snippets Manager replied on Sun, 2009/08/02 - 11:49pm

I'm working on a Tripod server (www.tripod.com), it must just be this Free server that's not allowing it or something

Snippets Manager replied on Sun, 2009/08/02 - 11:49pm

It's got to be the server I'm on or something, it's not working at all no matter what I do...

Snippets Manager replied on Sun, 2009/07/26 - 9:22am

yep! my friend just see at the source and copy paste,, same for the xml.. im hoping someone post how to match two inputs.. so i will not have need for php host..

Snippets Manager replied on Sun, 2009/07/26 - 9:22am

live example: http://poligoma.webs.com/XML/DB.htm

Snippets Manager replied on Sun, 2009/08/02 - 11:49pm

Wow, I must really suck at this stuff cuz I couldn't get any of this to work at all. Are there certain parameters that I need to change to make it work? I made the; index.xml , searchindex.js and pasted the form on an HTML page. none of it works at all.

Snippets Manager replied on Sun, 2009/07/26 - 9:22am

yep i got the images!! but not the two values search match.. anyone knows!! for(var i=0; i'); document.write('' + results[i].getAttribute("name") + '
'); document.write(''); document.write('' + results[i].getAttribute("age") + ''); document.write('' + results[i].getAttribute("height") + ''); document.write('' + results[i].getAttribute("weight") + ''); document.write(''); }

Snippets Manager replied on Mon, 2009/07/06 - 9:46pm

Hello- I've hacked this code a bit to write the search results, including xml attributes to an html table. // THE SAMPLE XML: <?xml version="1.0" encoding="utf-8"?> John Paul George Ringo // THE HTML WITH JAVASCRIPT (search.html) Search window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("index.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("index.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'searchme' var searchterm = document.getElementById("searchme").value; var allitems = xmlDoc.getElementsByTagName("item"); results = new Array; if (searchterm.length < 3) { alert("Enter at least three characters"); } else { for (var i=0;i 0) { // if there are any results, write them to a table document.write('New SearchYou searched for '+searchterm+'

'); document.write(''); document.write(''); for(var i=0; i'); document.write(''); document.write(''); document.write(''); document.write(''); document.write(''); } document.write('
NAMEAGEHEIGHTWEIGHT
' + results[i].getAttribute("name") + '' + results[i].getAttribute("age") + '' + results[i].getAttribute("height") + '' + results[i].getAttribute("weight") + '
'); document.close(); } else { // else tell the user no matches were found var notfound = alert('No results found for '+searchterm+'!'); } } Search:    
Hope this helps!

Snippets Manager replied on Fri, 2009/06/26 - 1:21pm

Has anyone answered the previous comments? I need to do the same and haven't been able to figure it out as yet. Any help would be much appreciated. Thank you, Kboddy

Snippets Manager replied on Sat, 2009/01/24 - 8:55am

Thank you so much for posting this code snippet. I am very much a beginner at this. How might the .js code be adapted so that other child elements are retuned along with ie. thanks again!

Snippets Manager replied on Tue, 2008/08/19 - 10:46am

How can I set this up so that it will return more information within my xml file for each 'item'? I want to provide more informationt hen just returning the item that they type in, like a description or stats or something.... Any help would be greatly appreciated. Thanks, Mike

Snippets Manager replied on Sun, 2009/07/26 - 9:22am

Thanks a lot guys!! this script help me a lot on my data work, and havent ever seen before on any page on the web!! but now my Question is, how can i retreive an image from the xml,, just like a profile pic for each data line.. <?xml version="1.0" encoding="utf-8"?> John Paul George Ringo and also how would be the script for two values??? eg. ?name=paul&weight=168 Thanks in advance!