Forum Moderators: open
I want to create an html form where a user enters a some text (an artists name for example) & then that string is used as the search string to find matches in my paintings.xml file and then return the results to a web page.
Can anyone point me in the direction of a tutorial for this.
Thank you for your help.
window.onload = loadIndex;
function loadIndex() { // load indexfile
if (document.implementation && document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument("", "", null);
xmlDoc.load("index.xml");
}
else if (window.ActiveXObject) {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.load("index.xml");
}
}
function searchIndex() {
if (!xmlDoc) {
loadIndex();
}
var searchterm = document.getElementById("searchme").value;
var allitems = xmlDoc.getElementsByTagName("title");
results = new Array;
if (searchterm.length < 2) {
alert("Enter at least two characters");
} else {
for (var i=0;i<allitems.length;i++) {
var name = allitems[i].lastChild.nodeValue;
var exp = new RegExp(searchterm,"i");
if ( name.match(exp) != null) {
results.push(allitems[i]);
}
}
showResults(results, searchterm);
}
}
function showResults(results, searchterm) {
if (results.length > 0) {
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 {
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);
}
}
[edited by: httpwebwitch at 3:06 am (utc) on Jan. 26, 2009]
[edit reason] normalized font size [/edit]
var item = document.createTextNode(results[i].lastChild.nodeValue);
That still points you to the 'title' element which you matched; to find others jump to the parent then find the child:
var itemobject = results[i].parentNode;
var item_title = itemobject.getElementsByTagName('title')[0];
var item_summary = itemobject.getElementsByTagName('summary')[0];
etc.