0% found this document useful (0 votes)
171 views

XML Based Search (HTML) Javascript) (Dom) (XML) (Search)

Uploaded by

Ricardo Mavigno
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views

XML Based Search (HTML) Javascript) (Dom) (XML) (Search)

Uploaded by

Ricardo Mavigno
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Create account or Username: Password: Log In

DZone Snippets

5909 users tagging and storing useful source code snippets

Never been to DZone Snippets before?


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

Simple Javascript/XML based search (See related posts)


Search DZone Snippets

Search

Popular @ dzone.com
IonMonkey: Mozilla’s new JavaScript JIT compiler

20 jQuery Table Plugins

CoffeeScript 1.1 Released

Top 10 tips on logging in Java

A Calculus Primer Part IV- Introduction To Inte...

Performance analysis of Stored Procedures with ...

Building an Effective Scrum Team

// 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>

to html javascript dom xml search by Wieland on Tue Sep 26 09:35:26 -0400 2006

Comments on this post


mike2587 posts on Aug 19, 2008 at 11:49
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
fatmess posts on Jan 24, 2009 at 09:03
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 <item>
ie.<age> <height> <weight>
thanks again!
kboddy posts on Jun 26, 2009 at 14:24
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
mapmaker posts on Jul 07, 2009 at 00:40
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"?>
<searchable_index>
<item name="John" age="22" height="5 ft 5 inches" weight="150">John</item>
<item name="Paul" age="25" height="5 ft 9 inches" weight="168">Paul</item>
<item name="George" age="27" height="6 ft 1 inches" weight="175">George</item>
<item name="Ringo" age="23" height="6 ft 3 inches" weight="180">Ringo</item>
</searchable_index>

// THE HTML WITH JAVASCRIPT (search.html)


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Search</title>
<script type="text/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);
}
}

// Write search results to a table


function showResults(results, searchterm) {

if (results.length > 0) {
// if there are any results, write them to a table

document.write('<div><a href="search.html">New Search</a></div>You searched for <b><i>'+searchterm+'</i></b><br><br>');


document.write('<table border="1" style="width: 100%;">');
document.write('<tr><th>NAME</th><th>AGE</th><th>HEIGHT</th><th>WEIGHT</th></tr>');
for(var i=0; i<results.length; i++) {
document.write('<tr>');
document.write('<td>' + results[i].getAttribute("name") + '</td>');
document.write('<td>' + results[i].getAttribute("age") + '</td>');
document.write('<td>' + results[i].getAttribute("height") + '</td>');
document.write('<td>' + results[i].getAttribute("weight") + '</td>');
document.write('</tr>');
}
document.write('<table>');
document.close();

} else {
// else tell the user no matches were found
var notfound = alert('No results found for '+searchterm+'!');
}
}
</script>

</head><body>
<form action=""><b>Search:&nbsp;&nbsp;</b><input id="searchme" type="text" size="20">&nbsp;&nbsp;<input value="Submit" onclick="searchIndex(

</body></html>
Hope this helps!
xcitrate posts on Jul 26, 2009 at 11:03
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"?>


<searchable_index>
<item photo="john.jpg" name="John" age="22" height="5 ft 5 inches" weight="150">John</item>
<item photo="paul.jpg" name="Paul" age="25" height="5 ft 9 inches" weight="168">Paul</item>
<item photo="george.jpg" name="George" age="27" height="6 ft 1 inches" weight="175">George</item>
<item photo="ringo.jpg" name="Ringo" age="23" height="6 ft 3 inches" weight="180">Ringo</item>
</searchable_index>

and also how would be the script for two values???

eg. ?name=paul&weight=168

<body>
<form action="">

<input id="searchme" type="text" size="20">


<input id="searchme2" type="text" size="20">

<input value="Submit" onclick="searchIndex(); return false;" type="submit">


</form>
</body>

Thanks in advance!
xcitrate posts on Jul 26, 2009 at 22:05
yep i got the images!! but not the two values search match.. anyone knows!!

for(var i=0; i<results.length; i++) {


document.write('<tr>');
document.write('<td>' + results[i].getAttribute("name") + '
');
document.write('<img src="' + results[i].getAttribute("image") + '"></td>');
document.write('<td>' + results[i].getAttribute("age") + '</td>');
document.write('<td>' + results[i].getAttribute("height") + '</td>');
document.write('<td>' + results[i].getAttribute("weight") + '</td>');
document.write('</tr>');
}
dspurg7310 posts on Aug 03, 2009 at 00:52
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.
xcitrate posts on Aug 03, 2009 at 11:43
live example: http://poligoma.webs.com/XML/DB.htm
xcitrate posts on Aug 03, 2009 at 11:50
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..
dspurg7310 posts on Aug 04, 2009 at 03:30
It's got to be the server I'm on or something, it's not working at all no matter what I do...
dspurg7310 posts on Aug 04, 2009 at 03:52
I'm working on a Tripod server (www.tripod.com), it must just be this Free server that's not allowing it or something
silverelizard posts on Aug 26, 2009 at 15:53
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.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">


<html><head><meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Search</title>
<script type="text/javascript">
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<allitems.length;i++) {
var name = allitems[i].getAttribute(searchtype);
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);
}
}

// Write search results to a table


function showResults(results, searchterm) {

if (results.length > 0) {
// if there are any results, write them to a table

document.write('<div><a href="search.html">New Search</a></div>You searched for <b><i>'+searchterm+'</i></b><br><br>');


document.write('<table border="1" style="width: 100%;">');
document.write('<tr><th>NAME</th><th>AGE</th><th>HEIGHT</th><th>WEIGHT</th></tr>');
for(var i=0; i<results.length; i++) {
document.write('<tr>');
document.write('<td>' + results[i].getAttribute("name") + '</td>');
document.write('<td>' + results[i].getAttribute("age") + '</td>');
document.write('<td>' + results[i].getAttribute("height") + '</td>');
document.write('<td>' + results[i].getAttribute("weight") + '</td>');
document.write('</tr>');
}
document.write('<table>');
document.close();

} else {
// else tell the user no matches were found
var notfound = alert('No results found for '+searchterm+'!');
}
}
</script>

</head><body>
<form name="frmMain" id="frmMain" action="">
<b>Search:&nbsp;&nbsp;</b><br><br>
<input type="radio" name="criteria" value="name" checked="checked">Name &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;
<input type="radio" name="criteria" value="age">Age &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;
<input type="radio" name="criteria" value="height">Height &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp;
<input type="radio" name="criteria" value="weight">Weight
<br><br>
<input id="searchme" type="text" size="20">&nbsp;&nbsp;<br><br>
<input value="Submit" onclick="searchIndex(); return false;" type="submit">
</form>

</body>
</html>

Hope this helps anyone who wanted to achieve the same effect.
emily_raw posts on Sep 01, 2009 at 19:24
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.
<item name="document" department="HR" download="link">John</item>
Shaun_ZA posts on Mar 31, 2010 at 07:50
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 <customer>Some customer</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<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);
}
}

function showResults(results, searchterm) {

if (results.length > 0) {
for (var i=0;i<results.length;i++) {
var Message = " is a Customer" + 'n'
+ "Call the Service Provider" + 'n'
+ "or re-type your search criteria"
var found = alert(+results+ 'Message');
}

} else {
// else tell the user no matches were found
var Message = " is not a Customer";
var notfound = alert(searchterm.toUpperCase() + Message);
}
}
mike248x posts on May 08, 2010 at 10:06
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.
blencorp posts on May 10, 2010 at 17:04
@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/


mike248x posts on May 11, 2010 at 01:27
Thanks. I will take a look at it. By the way, thanks for sharing your hard work.
RSM posts on Jul 21, 2010 at 07:43
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.
sethonfire posts on Sep 12, 2010 at 10:26
this, the original post & mapmaker's, doesn't seem to work in chrome and ie8 (currently installed). any idea why? any workaround?
sethonfire posts on Sep 18, 2010 at 01:18
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.


antony1411 posts on Dec 23, 2010 at 22:26
very good all the improvements but someone could add style to the results with CSS, please comment the solution.
Shaun_ZA posts on Mar 02, 2011 at 00:59
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<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);
}
}
function showResults(results,searchterm) {
if (results.length > 0) {
for (var i=0;i<results.length;i++) {
var newResults=string (results.value)
Message = " is an SPC Customer" + 'n'
+ "Call SPC" + 'n'
+ "or re-type your search criteria"
alert(newResults+ Message);
}
}
else {
// else tell the user no matches were found
Message = " is not an SPC Customer";
alert(+searchterm+ Message);
}
}

Here's the code for the html

<form name="frmSPC" id= "frmSPC" action="">


<h3><span class="green">SPC Search Form</span><br />
<label>Number:
<input name="spcsearch" type="text" class="searchform" id="spcsearch" tabindex="1" maxlength="9" />
<input name="Submit" type="submit" class="button" id="Submit2" accesskey="V" tabindex="2" onclick="searchIndex(); return f
<input name="Clear2" type="reset" class="button" id="Clear2" accesskey="l" tabindex="3" value="Clear" />
</label>
</h3>
</form>
dylan666 posts on Mar 04, 2011 at 04:20
Can you tell me how to display all child nodes for each result?
Thanks in advance
dylan666 posts on Mar 04, 2011 at 04:34
Sorry, I was wrong...
I have to search using "ID" and display all "User" element...
This is the XML

<Example>
<User>
<ID>95</ID>
<Age>29</Age>
<Name>Robert Hassen</Name>
<City >Paris</City >
<Nickname>usr93</Nickname>
<FileNames>
<FileName>Documents\Abcd.pdf</FileName>
</FileNames>
</User>
</Example>

Could you help me?

You need to create an account or log in to post comments to this site.

Click here to browse all 7181 code snippets

Related Posts
» split value from units in html javascript dom formatting
» change text in html javascript dom text
» change title with javascript in html javascript dom title
» Firefox 3 and input file in html javascript firefox dom
» Php xml Parser in c ruby rails sql html javascript linux apache unix osx windows date python hash regex css mysql php bash perl java string image xml find convert
shell series60 database xslt web array url c++ time rubyonrails http google text activerecord rexml math csharp file REBOL jonas jsfromhell raoni sinatra rscript
» CSS Rounded Corners in c ruby rails sql html javascript linux apache unix osx windows date python hash regex css mysql php bash perl java string image xml find
convert shell series60 database xslt web array url c++ time rubyonrails http google text activerecord rexml math csharp file REBOL jonas jsfromhell raoni sinatra rscript

Snippets originally developed by Peter Cooper and powered by Ruby On Rails.

Copyright © 2007 DZone, Inc.

You might also like