Jump to content

Using RegExp in JS to test an XML file


Johnshellshock

Recommended Posts

Hi there I am stuggling with using JS to access a xml file I have built.I have a website which has over 200 backing tracks listed in numerical order wrtten out in HTML.Now I wish to add a search option to it . So I have buit a xml file for the tracks which I have been able to access using JS and get it to display a page as I want it.I have managed to build a form which reacts with the JS I have written so far.Here it is below.<form name="myform" action="" method="GET">Search By Artist <input type="text" name="inputbox" value="" class="searchboxtext30" size="40" maxlength="30" /><input type="button" name="button" value="Submit" onclick="loadXMLDoc(this.form)"/></form><div id="myDiv"> </div>What I want to do is whatever the user inputs via the form is to have some JS evaluate it aginst my xml file.Here is what I have writen so far<script type="text/javascript">function loadXMLDoc(form){if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) } xmlhttp.open("GET","XML Data.xml",true); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; { var TestVar=form.inputbox.value; var patt1=new RegExp("var=TestVar"); var x=xmlDoc.getElementsByTagName("track");for (i=0;i<x.length;i++) document(patt1.test(x.getElementsByTagName("artist")[0].childNodes[0].nodeValue)); } if patt1==true { alert ("You Have A Match: " + TestVar); } else { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","Text.txt",true); xmlhttp.send();}</script>Now I do not understand how to tie the RegExp command in to my input ie form.inputbox.value and then get it to search through my xml file to see if there is a match on the Artist Tag and then give a true or flase result which I can then use to carry out futher actions.For the time being I am using an alart box as I am doing this job stage by stage.

Link to comment
Share on other sites

There's a lot more going wrong here than you think.1. For your regex, try new RegExp(TestVar)2. Your curly braces are mismatched. You probably want one after your initial for-loop statement3. There is no function called "document"; the statements in your for-loop should be testing a condition. Replace the word "document" with the word "if" and it might work.4. That means your alert and else clause need to be in the for-loop also. Simply remove if patt1==true. It's missing its parentheses, for one thing. And it's not the test you want to make. patt1 is your regex. It will never equal true. patt1.test etc. is the test. Everything else has to hang on that.5. Everything (or mostly everything) you currently have after xmlhttp.send() should actually be in your onreadystatechange function. xmlhttp.responseXML has no value until your xml document is returned. You'll know that's happened when the onreadystatechange function is called.6. I'm not sure where or why you should access Text.txt, but you don't want to do it where you're currently doing it, because it happens almost immediately after you request the xml document. I'm not sure what the result will be exactly, but it won't be what you expect.

Link to comment
Share on other sites

Thanks for your input.I have decided to go back to first principles First here is code which does work but only tells me that my input on the form works and also produces the required fail message when required.In this case if I input 'a'<script type="text/javascript">function Inputfromform(form){ { var TestVar=form.inputbox.value; alert ("You typed: " + TestVar); } if (TestVar=="a") {if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","Text.txt",true);xmlhttp.send(); }}</script>You can see it here Alert box and Fail messageSo far so good now for my attempt to use RegExp test my understanding beingthat it will produce either true or false output. so from this I can then go in for futher processing.<script type="text/javascript">function Inputfromform(form){ { var TestVar=form.inputbox.value; alert ("You Have A Match: " + TestVar); } //code to evaluate form.inputbox.value which shouold give either a "true" or "false" result var TestVar2=new RegExp("TestVar"); {if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { TestVar2.test(x.getElementsById("artist")[0].childNodes[0].nodeValue); } }xmlhttp.open("GET","XML Data.xml",true);xmlhttp.send();var x=xmlDoc.getElementsByTagName("track");for (i=0;i<x.length;i++) } if (TestVar2.test=="true") { alert ("You Have A Match: " + TestVar2); }//Fail Message Code else (TestVar2.test=="false") {if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","Text.txt",true);xmlhttp.send(); }}</script>You can see it hereTrying to use RegExpWhat I am not sure about is the correct way to use RegExp ie declare it and how to use it to test the strings in the "Artist" node of my xml file so that I get a return of either true or false

Link to comment
Share on other sites

As I wrote before. All or most of the code that currently follows your first xmlhttp.send() statement needs to be in your xmlhttp.onreadystatechange function.Also, I was not mistaken when I removed the quotation marks from this regular expression constructor: new RegExp(TestVar). You need to pass the value of TestVar. If you pass "TestVar" then the regular expression will look for strings that match the literal string "TestVar," not the value you pull out of your text input.

Link to comment
Share on other sites

Fair point on the new RegExp(TestVar) I have corrected this my fault for not spotting thisI am not sure if I understand what you mean by "All or most of the code that currently follows your first xmlhttp.send() statement needs to be in your xmlhttp.onreadystatechange function" I have repositioned the code as I think I understand waht you are saying.I am sure you will tell me otherwise if it is still not correct.See Below<script type="text/javascript">function Inputfromform(form){ { var TestVar=form.inputbox.value; // alert ("You Have A Match: " + TestVar); } //code to evaluate form.inputbox.value which shouold give either a "true" or "false" result var TestVar2=new RegExp(TestVar); {if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var x=xmlDoc.getElementsByTagName("track");for (i=0;i<x.length;i++) TestVar2.test(x.getElementsById("artist")[0].childNodes[0].nodeValue); } }xmlhttp.open("GET","XML Data.xml",true);xmlhttp.send(); } if (TestVar2.test=="true") { alert ("You Have A Match That is True: " + TestVar); }//Fail Message Code else (TestVar2.test=="false") {if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); }else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","Text.txt",true);xmlhttp.send(); }}</script>When I loaded this up all I get is the Fail message displayed ie the code from else (TestVar2.test=="false")

Link to comment
Share on other sites

That fail message is because you cannot put a conditional test after the word else. It is permitted after the words else if, but that is not what you need here. You can safely remove those parentheses and everything in them. The code following the word else will be executed if TestVar2.test does not equal "true." Adding another condition to test will do nothing.Going from the way the JavaScript interprets your curly braces, this is your entire readystate function:

xmlhttp.onreadystatechange = function(){   if (xmlhttp.readyState==4 && xmlhttp.status==200)   {	  var x=xmlDoc.getElementsByTagName("track");	  for (i=0;i<x.length;i++)		 TestVar2.test(x[i].getElementsById("artist")[0].childNodes[0].nodeValue);   }}

If I add some curly braces to make your for-loop more sensible, it looks like this:

xmlhttp.onreadystatechange = function(){   if (xmlhttp.readyState==4 && xmlhttp.status==200)   {	  var x=xmlDoc.getElementsByTagName("track");	  for (i=0;i<x.length;i++)	  {		 TestVar2.test(x[i].getElementsById("artist")[0].childNodes[0].nodeValue);	  }   }}

The problem is that the function does absolutely nothing productive. It attempts to match the value of each "track" node against your regular expression, but it does not assign the return value of the test to anything, and even if it did, there are no additional lines of code in the function. (And you have forgotten to define xmlDoc.) What you need is something like this:

xmlhttp.onreadystatechange = function(){   if (xmlhttp.readyState==4 && xmlhttp.status==200)   {	  var xmlDoc=xmlhttp.responseXML;	  var x=xmlDoc.getElementsByTagName("track");	  var trackValue;	  for (var i=0;i<x.length;i++)	  {		 trackValue = x[i].getElementsById("artist")[0].childNodes[0].nodeValue;		 if (TestVar2.test(trackValue) == true)		 {			alert ("You Have A Match That is True: " + trackValue);		 }	  }   }}

Link to comment
Share on other sites

Thanks for that it does make sense I have inputed the code as you have suggested but still no luck

<script type="text/javascript">function Inputfromform(form){     {    var TestVar=form.inputbox.value;     // alert ("You Have A Match: " + TestVar);     }	 	//code to evaluate form.inputbox.value which shouold give either a "true" or "false" result var TestVar2=new RegExp(TestVar);           {if (window.XMLHttpRequest)    {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest();    }else    {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");    }xmlhttp.onreadystatechange = function(){   if (xmlhttp.readyState==4 && xmlhttp.status==200)   {      var xmlDoc=xmlhttp.responseXML;      var x=xmlDoc.getElementsByTagName("track");      var trackValue;      for (var i=0;i<x.length;i++)      {         trackValue = (x[i].getElementsTagId("artist")[0].childNodes[0].nodeValue);         if (TestVar2.test(trackValue) == true)         {            alert ("You Have A Match That is True: " + trackValue);         }      }   }}xmlhttp.open("GET","XML Data.xml",true);xmlhttp.send();          }//Fail Message Code              else //(TestVar2.test=="false")     		     {if (window.XMLHttpRequest)     {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();     }else     {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");     }  xmlhttp.onreadystatechange=function()  {    if (xmlhttp.readyState==4 && xmlhttp.status==200)     {    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;     }	  }xmlhttp.open("GET","Text.txt",true);xmlhttp.send();         }}</script>

A sample of my xml file XML Data.xml<?xml version="1.0" encoding="utf-8"?> <backing_tracks> <track> <number>SSBV001</number> <title><a href="htm Tracks Files/Get%20Ready%20Backing%20Vocals.htm" class="style4" onclick="MyWindow=window.open('http://www.shellshockmusic.co.uk/htm Tracks Files/Get Ready Backing Vocals.htm','MyWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=300,height=150'); return false;">Get Ready</a> </title> <artist>The Temptations</artist> <key>C</key> </track> <track> etc

Link to comment
Share on other sites

Yes, it's frustrating to put together a whole bunch of code and debug it in sections. For the future, a better way to develop is one section at a time. Make sure one part of the mechanism is correct before adding more complexity to it.Fortunately, we are getting closer. Here is an immediate problem. This line (and the lines that follow it):else //(TestVar2.test=="false")is not dependent on a prior if statement. It's just out there. I believe your intent is for that code section to come after this:if (TestVar2.test(trackValue) == true){alert ("You Have A Match That is True: " + trackValue);}So you might try moving it. That's really going to make your structure hard to read, with so many tasks nested inside each other. You might consider extracting some of these tasks from this big function and splitting them off into separate functions.I guess you are not taking advantage of Firefox's built-in Error Console. When you load the current document into Firefox, and then look at the most recent entry in the Error Console, you will see that it pinpoints that else statement as the source of the trouble. It doesn't tell you how to fix it (as I just did) but it gives you a place to start looking. I suggest adding the Error Console to your developing routine.

Link to comment
Share on other sites

I have put the else statement after the if statement still no joy however when using the Firefox error console no errors come up and thanks for that tip Here is the current coding

<script type="text/javascript">function Inputfromform(form){     {    var TestVar=form.inputbox.value;     // alert ("You Have A Match: " + TestVar);     }	 	//code to evaluate form.inputbox.value which shouold give either a "true" or "false" result var TestVar2=new RegExp(TestVar);           {if (window.XMLHttpRequest)    {// code for IE7+, Firefox, Chrome, Opera, Safarixmlhttp=new XMLHttpRequest();    }else    {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");    }xmlhttp.onreadystatechange = function(){   if (xmlhttp.readyState==4 && xmlhttp.status==200)   {      var xmlDoc=xmlhttp.responseXML;      var x=xmlDoc.getElementsByTagName("track");      var trackValue;      for (var i=0;i<x.length;i++)      {         trackValue = (x[i].getElementsTagByName("artist")[0].childNodes[0].nodeValue);         if (TestVar2.test(trackValue) == true)              {            alert ("You Have A Match That is True: " + trackValue);              }		              //Fail Message Code                                 else //(TestVar2.test=="false")     		                            {                      if (window.XMLHttpRequest)                            {// code for IE7+, Firefox, Chrome, Opera, Safari                      xmlhttp=new XMLHttpRequest();                            }                      else                            {// code for IE6, IE5                      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");                            }                      xmlhttp.onreadystatechange=function()                            {                        if (xmlhttp.readyState==4 && xmlhttp.status==200)                                 {                      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;                                 }	                            }                      xmlhttp.open("GET","Text.txt",true);                      xmlhttp.send();                                  }		       }   }}xmlhttp.open("GET","XML Data.xml",true);xmlhttp.send();          }}</script>

Link to comment
Share on other sites

Cool beans. You're very close.1. Notice that the name of the function called by your form button does not match the name of the function in your script. That's an easy fix. Your Error Console should have caught that the first time you tried to run this thing.2. While you're doing that, I suggest NOT capturing your submit button's click event, but rather capturing the form's submit event. The reason is that hitting the return/enter key while the focus is on your text input will cause a submit event, and then you'll be in trouble. So remove onclick="loadXMLDoc(this.form)" from your button, and add this to your form tag: onsubmit="loadXMLDoc(this); return false". There are slicker ways to do that, but this will be fine.3. I laughed when my Error Console turned this up. Look carefully: x.getElementsTagByName. It's so close to correct that anyone could miss the error.I'm pretty sure those are the only substantive fixes you need, but I could have forgotten some other tweak I made. Additional things to consider:For my own sanity, I removed a bunch of needless {curly braces} while I studied this thing. I suggest you do the same.Now that I've seen your xml, I suggest changing your regex constructor to this: new RegExp(TestVar, "i"); The i modifier makes it case insensitive. I assume you'll want a match if your user enters "temPtations" instead of "Temptations"?There still may be issues with the content of your xml document. If it parses with all those icky nested quotation marks, then it parses. And if your server is OK with a space in the filename, ok.But it seems wasteful to store an HTML <a> tag with all that inline script when it would be so easy for JavaScript to build the tag dynamically using data from the <track> element. If every item in the file looks like that, you could significantly lighten the xml.(BTW, you are testing this on your server, right? AJAX can fail on your desktop.)I sure hope you've learned something about AJAX syntax through all this, and also a few debugging techniques. I could have just written the whole thing for you to begin with, but we hope people learn things, too.Lemme know how it turns out.

Link to comment
Share on other sites

At last it now seems to workAs regards to the name of the fuction when I wrote my second version of the JS I changed to name to Inputfromform and put this name in both my form and in the call fuction name.With replacing the onclick="loadXMLDoc(this.form)" from my button and replacing it with onsubmitt="loadXMLDoc(this);return false in the form Tag I was unable to get it to work when I ran an error check in Adobe Dreamweaver 3 I got thr following error message The Tag Input doesn't have an attribute in currently active versions [XHTML1.0 Transitional].Note I subsituted Inputformform for XMLDoc.Below is my current code for the form.

<form name="myform" action="" method="GET">Search By Artist <input type="text" name="inputbox" value="" class="searchboxtext30" size="40" maxlength="30" /><input type="button" name="button" value="Submit" onclick="Inputfromform(this.form)"/></form>

Yes that error is now so obvious! now you mention it. I have found a useful feature on Dreamweaver is the expand all and collapse fuctions makes sorting Brackets braces what ever you wish to call them a bit easier.The change that got the JS to work was renaming my XMLfile from XML Data.xml to XMLData.xml.Upon this change things started to work.The strange thing is I used the XML Data.xml ok with JS to write tables in could this be to do with the fact that I am using AJAX. Once I have the table sorted I think I am going to have a go at writing seperate functions so as to make the writing of the required code a little bit easier.

Link to comment
Share on other sites

If I understand correctly, you tried to replace the onclick attribute with the onsubmit attribute? Doing that would generate exactly the error that was reported. The actual idea is to remove the onclick attribute from the button tag and add the onsubmit attribute to the form tag.Yeah, as I said, I wondered about that space in the filename. Some operating systems are cool with that, and some are not. I make it a practice never to use spaces so that I'm always covered.I'm glad that you'll be pulling out code and writing smaller functions. Some famous computer scientist (I don't remember who) once said that a good function should never be more than 10 or 12 lines long. Maybe an exaggeration, but you get the point. A short chunk of code is easy to understand and easy to debug. A big chunk of code can be hard to follow and hard to debug.First rule of thumb. If a script ever needs to execute essentially the same chunk of code in more than one location, pull it out and make it a function. The idea is that a lot of code can be reused, and when you've written a few apps, you'll find yourself saying, "Hey! I don't need to code that. I already have a function that does that." And the other benefit there is that when you have a function you've tested in a lot of situations, you can paste it into a script and know that it'll probably work as expected. So that if you're calling it from FunctionA, and FunctionA needs debugging, you'll have at least one section that you can skip over.Example. Most AJAX apps I've seen have a separate function just for creating an xmlhttp object. You could use one of those right away, and it would take you maybe 5 minutes to do it.

Link to comment
Share on other sites

I have managed to write a AJAX app for the xmlhttp object . If my understanding is correct do I always need to have the function declared at the start of the JS and then use it required.Anyway below is the script that works

<script type="text/javascript">function loadXMLDoc(url,cfunc){if (window.XMLHttpRequest)  {// code for IE7+, Firefox, Chrome, Opera, Safari  xmlhttp=new XMLHttpRequest();  }else  {// code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }xmlhttp.onreadystatechange=cfunc;xmlhttp.open("GET",url,true);xmlhttp.send();}function Inputfromform(form){     {    var TestVar=form.inputbox.value;     // alert ("You Have A Match: " + TestVar);     }	 	//code to evaluate form.inputbox.value which shouold give either a "true" or "false" result var TestVar2=new RegExp(TestVar,"i");  {loadXMLDoc("XMLData.xml",function()    {   if (xmlhttp.readyState==4 && xmlhttp.status==200)      {      var xmlDoc=xmlhttp.responseXML;      var x=xmlDoc.getElementsByTagName("track");      var trackValue;      for (var i=0;i<x.length;i++)           {         trackValue = (x[i].getElementsByTagName("artist")[0].childNodes[0].nodeValue);			 	if (TestVar2.test(trackValue) == true)              {            alert ("You Have A Match That is True: " + trackValue);              }		              //Fail Message Code                                 else //(TestVar2.test=="false")     		                  {                      loadXMLDoc("Text.txt",function()                              {                        if (xmlhttp.readyState==4 && xmlhttp.status==200)                                 {                      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;                                 }	                              });                                            }		            }      }    });  }          }</script>

The only tricky bit is putting the ); after the right set of {brackets!!Now as regards to the Input form below is the existing form code

<form name="myform" action="" method="GET">Search By Artist <input type="text" name="inputbox" value="" class="searchboxtext30" size="40" maxlength="30" /><input type="button" name="button" value="Submit" onclick="Inputfromform(this.form)"/></form>

I have modified it as I think I understand your suggestion see below

]<form name="myform" onsubmit="Inputfromform(this);return false" method="GET">Search By Artist <input type="text" name="inputbox" value="" class="searchboxtext30" size="40" maxlength="30" /><input type="button" name="button" value="Submit"/></form>

However it does not work

Link to comment
Share on other sites

Better than you think. :)I bet you did not try submitting the form by hitting enter/return when the focus was on your text input. Try that, and it works fine. It doesn't work when you click the button because that input needs to be type="submit" . I should have noticed that sooner. Make that change and you're good to go.

Link to comment
Share on other sites

Hi there I have changed the input to type="submit" as below

<form name="myform" action="" onsubmit="Inputfromform(this);return false" method="GET">Search By Artist <input type="text" name="inputbox" value="" class="searchboxtext30" size="40" maxlength="30" /><input type="submit" name="button" value="Submit"/></form>

Note I have put in the form line action="" so as to pass validation on adobe dreamwaever as I was getting a error message.After the input I have put the following to eliminate someone just pressing the buton and getting a false positve as all artist names have spaces in them and if you enter nothing they all come up

 {    var TestVar=form.inputbox.value;        }	 	 //code to eliminate space as a input	 	 if (TestVar=="")	                  {                      loadXMLDoc("Text.txt",function()                              {                        if (xmlhttp.readyState==4 && xmlhttp.status==200)                                 {                      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;                                 }	                              });                                            }		          	 else

followed by rest of codeNow having got this far I now need to work out a method of writing a table of tracks which have the result true.I have noticed that if I get just one false or more I get a error message whereas what I really want is the error message to only appear if all matchs give a false result.I think I need a pointer as to where to go next as I know what I want but unsure as how to get it.For example if input is The Supremes I want to have a table with just those tracks which match displayed in the same format as I am displaying my tracks on my existing pages

Link to comment
Share on other sites

You could also get false positives if they enter the word "the", too. Also, I think entering just "d" (for example) will bring up Diana Ross but also the Doors. (Maybe that's okay. I don't know how you want the system to work.) Anyway, you might want a more sophisticated regular expression. One way to prevent the error message and keep looping through the tracks is to set a flag. Declare a flag variable as false right before the loop. If you get a match, set the flag to true. It doesn't matter if the loop sets the flag to true multiple times. After the loop, if the flag is still false, then run your error routine. Otherwise, skip over it.These links will help you create a table on the fly. The first and last come from the XML tutorials, but they are legitimate HTML methods also. If you're used to XML, you probably know them already.http://www.w3schools.com/dom/met_document_createelement.asphttp://www.w3schools.com/jsref/met_table_insertrow.asphttp://www.w3schools.com/jsref/met_tablerow_insertcell.asphttp://www.w3schools.com/dom/dom_nodes_add.aspIn a nutshell, do this:create a table elementcreate a tbody elementappend the tbody to the tableinsert a row in the tbody (all table methods are available to a tbody element; this is not widely documented)insert a cell in the table rowadd content to the cell's innerHTML(make as many rows and cells as you need)append or insert the table in the correct parent elementYou could also write a table and tbody into your HTML. Use CSS to set the table's display property to none. When you need to add content, you'll only need to insert rows and cells. Then set the table's display property to something visible.

Link to comment
Share on other sites

One way to prevent the error message and keep looping through the tracks is to set a flag. Declare a flag variable as false right before the loop. If you get a match, set the flag to true. It doesn't matter if the loop sets the flag to true multiple times. After the loop, if the flag is still false, then run your error routine. Otherwise, skip over it.I have tried to set up a flag as you have suggested but what is interesting is that it works fine when I input a value that matches some of the song titles I get a positive and no error message just as I want.However if I input a diliberate fail say for example "Z" the error message does not come up. Below is the coding

function Inputfromform(form){     {    var TestVar=form.inputbox.value;     // alert ("You Have A Match: " + TestVar);    //setting flag    var flag=false;     }	 	 //code to eliminate space as a input	 	 if (TestVar=="")	                  {                      loadXMLDoc("Text.txt",function()                              {                        if (xmlhttp.readyState==4 && xmlhttp.status==200)                                 {                      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;                                 }	                              });                                            }		          	 else{	//code to evaluate form.inputbox.value which should give either a "true" or "false" result var TestVar2=new RegExp(TestVar,"i");  {loadXMLDoc("XMLData.xml",function()    {   if (xmlhttp.readyState==4 && xmlhttp.status==200)      {      var xmlDoc=xmlhttp.responseXML;      var x=xmlDoc.getElementsByTagName("track");	 	       var trackValue;      for (var i=0;i<x.length;i++)           {         trackValue = (x[i].getElementsByTagName("artist")[0].childNodes[0].nodeValue);			   		 	if (TestVar2.test(trackValue) == true)			               {			 flag=true;			               alert ("You Have A Match That is True: " + trackValue + flag);			               }			                  }      }    });   } }  //Fail Message Code                                 if (flag=false)//(TestVar2.test=="false")     		                  {                      loadXMLDoc("Text.txt",function()                              {                        if (xmlhttp.readyState==4 && xmlhttp.status==200)                                 {				      //alert (flag);			                      document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;					                                   }	                              });                                            }		  	   		         	    }

If I have understood things correctly if I get a true result I then reset the flag to true as in flag=true; and I have put the error rutine after the loop.Am I doing somthing daft?

Link to comment
Share on other sites

1. if (flag = false) needs to be if (flag == false)2. The flag routine needs to be inside your readystate function. This should be simple cut and paste. Initialize the flag right before your for-loop. Put the if(flag...) structure right after the for-loop. I mean right after the }brace that closes the for-loop. (Right now, it's positioned after several other structures have closed, so it won't trigger correctly, if at all.)I'm pretty sure that little bit of repositioning will work.

Link to comment
Share on other sites

Yes you are right it does work as it should.Now for the fun & games in creating the required table on the fly.The First thing I will do is go through the 4 examples you reconmended.I will let you know how I get on. As regards to using a more sophisticated regular expression I think it would be nice to have one that eliminated the word "the" as a lot of groups have tat word in there name ie the beatles the kinks etc.

Link to comment
Share on other sites

I have started to build the table so far I have just created the table and the table header.When using the firefox error console I get no errors but I can not get it to display. You can view it at http://www.shellshockmusic.co.uk/search128.html

                           { 		    			//Declare variables and create table, tableheader and tablebody			var oTable=document.createElement("table");			var oThead=document.createElement("thead");				//var oTbody=document.createElement("tbody");			//var oRow,oCell;			//var i,j;						//Declare Table Headings			var heading = new Array();			heading[0] = "Track";			heading[1] = "Song Title";			heading[2] = "Artist";			heading[3] = "Key";			heading[4] = "Buy Now";			heading[5] = "View Cart";				//Insert the created elements into table			oTable.appendChild(oThead);			//oTable.appendChild(oTbody);									//Set the table's width border alignment and color			oTable.width=926, border=1, align='centre', bgcolor='#c0c0c0';						//Insert a row into the header and set its background color			oRow=document.createElement("tr");			oThead.appendChild(oRow);			oThead.bgcolor='#a8a8a8';				    //Create and insert cells into the header Row						{			oCell=document.createElement("th");			oCell.innerHTML=heading[0];			oRow.appendChild(oCell);			oRow.width=67,class='style2';			}						{			oCell=document.createElement("th");			oCell.innerHTML=heading[1];			oRow.appendChild(oCell);			oRow.width=399,class='style2';			}						{			oCell=document.createElement("th");			oCell.innerHTML=heading[2];			oRow.appendChild(oCell);			oRow.width=163,class='style2';			}						{			oCell=document.createElement("th");			oCell.innerHTML=heading[3];			oRow.appendChild(oCell);			oRow.width=29,class='style2';			}						{			oCell=document.createElement("th");			oCell.innerHTML=heading[4];			oRow.appendChild(oCell);			oRow.width=121,class='style2';			}						{			oCell=document.createElement("th");			oCell.innerHTML=heading[5];			oRow.appendChild(oCell);			oRow.width=107,class='style2';			}									document.getElementById("myTable").responseText;			                         }

I am trying to link it to the following code in the body of the page

<div id="myTable"> </div>

Link to comment
Share on other sites

Did you change it everywhere? You have that syntax in several different places.Also, to set a class you need to use className:oRow.className = 'style2';(I'm referring to these lines:oRow.width=67,class='style2';if you haven't guessed)

Link to comment
Share on other sites

First off I have changedoRow.width=67,class='style2';tooRow.style.width = '67px';oRow.className = 'style2';Thanks for the inputI think the problem I have is how to append the table to the div would using the following expression do the trick?myTable.appendChild(oTable);and if so where would I put it

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...