JavaScript - Searching Array Basic Code Problem
Code:
<html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["a", "b"]; Items [1] = ["c", "d"]; var i = 0; if(Items [i++][0] == "c"){ document.write("hello"); } </script> </script> <body> </body> </html> so im trying to search an array with this function its not working i tried using firebug but it showed no errors. I think its the i++ part i want to increment i each time it tries it. WAIT SORRY I SOLVED IT I solved it you can put in Pistol or shotgun for name Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["Pistol", "50", "2000"]; Items [1] = ["shotgun", "5000","1000"]; var i = 0; function chek(){ if(Items [i][0] == document.getElementById("name").value){ document.getElementById("a").value = Items [i] [1]; document.getElementById("acc").value = Items [i] [2]; i=0; } else { i++ } } </script> </script> <body> Dammage<input type="text" id="a" /> <br/> ACC<input type="text" id="acc" /> <br/> Name<input type="text" id="name" /> <br/> <input type="button" onclick="chek();" value="Chek" /> </body> </html> Is there anyway to make it more streamline so you dont have to click to increment? Similar TutorialsHi guys, I have an array which looks like this: var v=["It is my birthday today. ","How are you today. ","The weather is nice today. "]; I then, by using a function need to search for a specific word in the array, and if it is there, it alerts the word and "found", and if it isnt, it alerts the word and "not found". In the function below, a is the string/word which will be searched for in the array, and b is the array location to be searched. Therefore, if wordfind("birthday",0) was typed in, the value would be found. However, the code I have below is not working as I do not know how to make it so it knows that b is the array index to be searched and that a is the string value that will be searched for. Code: function wordfind(a,b){ var find = b.search(a) if(find==-1) alert(a+" not found") else alert(a+" found") } wordfind("birthday",0) Any help on this would be fantastic, Mike Hi guys, I'm trying to write a function such that it can be called, with a particular string specified in the call, and the function will then search a pre-defined array ("pages") of webpage URLs and headers in the form ["[www.sampleurl1.com] Sample Header 1. ", "[www.sampleurl2.com] Sample Header 2. "]; etc. etc., to see if the aforementioned string occurs in the "header" part of any of the indexes of the "pages" array, and then if it does, to alert "Found in x,y,z" where x y and z are the indexes of the "pages" array in which the specified string was found to occur. Here is what I have so far: Code: var pages=["[www.lboro.ac.uk] Loughborough University. ", "[www.oxford.ac.uk] Oxford University. "]; var founds=[] function findIdxsC(s){ for(i=0;i<pages.length;i++) if((pages[i].substring(pages[i].indexOf("]") + 1,pages[i].lastIndexOf("."))).match(/s/)) founds.push(pages[i]) } var array=founds.filter(findIdxsC) var arr2str=array.toStr; alert("Found in "+arr2str); findIdxsC("nIvERsi"); In theory, the above example should alert "Found in 0,1" because I have used the "match" command (so the search is case-insensitive) and the string "niversi" is found in the "header" parts of indexes 0 and 1. However, what it actually alerts is "Found in undefined". As far as I can see the problem lies with either the if-statement(and the associated command to "push" the indexes of "pages" for which the condition applies, to a new array, "founds") or with the filter and toString commands used towards the end. Perhaps it is one of these, or perhaps there is something else I am missing? Either way I would appreciate it if anyone could identify what in my code is causing the "Found in undefined" alert and suggest how I could rectify it, as it's causing me a bit of a headache Many thanks All right, to start, I'll summarize what I'm doing currently... - Asks the User to select a date (year, month, day) via drop-down boxes - Converts whatever the user inputs to a formal that will match a string value found in an imported array in a .js file ... And what I'm having trouble with: - Searching through the imported array for a matching value - Printing whatever block of the array matches the value, as well as any others that also match the value. For starters, because the array I'm working with is enormous, I'll just make one up here that is still in the same format. In working with the main code, assume that this is the cdr.js file: Code: var cdr = [ { "callid": "Guest User1", "start": "2009-05-11 15:08:40", "end": "2009-05-11 15:09:46", "duration": "66", }, { "callid": "Guest User2", "start": "2009-05-11 16:09:40", "end": "2009-05-11 16:09:47", "duration": "7", }, { "callid": "Guest User3", "start": "2009-05-12 12:10:30", "end": "2009-05-12 12:10:56", "duration": "26", }, { "callid": "Guest User4", "start": "2009-05-13 17:25:30", "end": "2009-05-13 17:26:30", "duration": "60", } ]; So basically I want the search to be based on that "start" value, though only the date (which I assume would be doable by using .substring()) Now here is the actual code of the program: Code: <html> <head> <script type="text/javascript" src="cdr.js"></script> <script> function init() { // Grab the values that the user has entered var theYear = (document.myForm.inputYear.value); var theMonth = (document.myForm.inputMonth.value); var theDay = (document.myForm.inputDay.value); // Convert them to something that will match the string theDate = (theYear + "-" + theMonth + "-" + theDay); // The search needs to go here } </script> <head> <body> Select a date which you would like to view the call statistics of: <form name="myForm"> <select name ="inputYear"> <option value="2009">2009</option> <option value="2008">2008</option> <option value="2007">2007</option> <option value="2006">2006</option> <option value="2005">2005</option> <option value="2004">2004</option> </select> <select name ="inputMonth"> <option value="01">January</option> <option value="02">Februrary</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select> <select name = "inputDay"> <option value="01">1</option> <option value="02">2</option> <option value="03">3</option> <option value="04">4</option> <option value="05">5</option> <option value="06">6</option> <option value="07">7</option> <option value="08">8</option> <option value="09">9</option> <option value="10">10</option> <option value="11">11</option> <option value="12">12</option> <option value="13">13</option> <option value="14">14</option> <option value="15">15</option> <option value="16">16</option> <option value="17">17</option> <option value="18">18</option> <option value="19">19</option> <option value="20">20</option> <option value="21">21</option> <option value="22">22</option> <option value="23">23</option> <option value="24">24</option> <option value="25">25</option> <option value="26">26</option> <option value="27">27</option> <option value="28">28</option> <option value="29">29</option> <option value="30">30</option> <option value="31">31</option> </select> <input type="button" onclick="init()" value="View Date"> </form> </body> </html> I've essentially left the section where the search code needs to be blank as I'm not even sure where to begin. Any help would be appreciated. I'm looking to find a way to search through javascript in the current document and save certain lines into an array. If the code had been in a div, I could easily use something like document.getElementById("Something".value but in this case, the code is in the header and I'm not positive how to read the information. Any suggestions would be a great help. I feel stupid for asking a question about searching arrays, when there's a very similar thread that has been answered just recently on the first page; however, I'm still having trouble contemplating my own scenario. Basically, my program prompts the user for the length of the array and then asks the user to fill the array with words. Here is where I need help: I want to confirm if the user wants to search the array for those words. If so, the user will then be prompted to enter the word he wishes to search for; if found, the location of that word will be reported and the number of times the word has been searched for will be kept track of in a separate array. Here is what I have so far: Code: /* -- phase 3 ------------------------------------------------------ search for words the user asks for */ // search variables var response; var search; while (true) { // confirmation protocol response = confirm("Do you wish to search the lexicon for a word?") if (response) { search = prompt("What word would you like to search for?"); // alert("search"); } else { alert("Thank you for wasting my time."); break; } // begin search protocol for (i=0; i<words.length; i++) { if (search==words[i]) { alert("Word found at" +i+);} } // end for loop else {alert("word not found.");} // counter array/accumulator var hits = new Array(words.length); hits[i] = 0; for (i=0; i<words.length; i++) { if (words[i] == search) { hits[i] = hits[i] + 1; alert("This word has been searched for " +hits[i]+ "times."); } } // end for loop } // end while The problem with my search seems to be that the search is parsed through the for loop; if it finds the word it alerts me that it was found at i location, but then it continues through and sees that the search does not equal the other values in the array and reports it's not found as well. My counter array is completely off, and I'm really at a loss to figure it out. I can see that the problem might be that each new search resets the hits[i] to equal 0, so no matter how many times a word is searched for, it returns a count of 1. I really want this array to track the number of hits for each word searched for, but have no clue why it's not working. Thanks for any help I can get; and please, feel free to critique my coding style, I definitely need to improve. hey guys im not new to javascript but arrays still confuse me exspecialy when put into loops ok say i had 2 arrays i have used jquerry to extract a question lets say this is the question How long is a piece of string? the answer is for this example infinite so what i want to do is search the question trough a array with 21984 and more in the future when it finds the match it then looks at the answers array at the same array length as where the question was found then sends the answer to a variable for later use could someone give me a example on how to do this please? Hi, I am trying to search an array for a string and then if it is found alert it. I have found examples of how to iterate the array and how to use .IndexOf to return a true false statement as to whether the array includes the string, but i don't know what to do after that and how to display the string if its found. Any help appreciated.. Thanks This is very basic yet i can find the answer. How do you stop a countdown function?
Code: <html> <head> <title>Click the button</title> <script type="text/javascript"> function x() { window.alert('1'); window.alert('2'); window.alert('3'); } document.getElementById("y").onclick = x; </script> </head> <body> <form> <input type="button" value="Click the button" id="y" /> </form> </body> </html> By the way... Are there any good websites / validators that can be helpful in situations like that? I've been looking at this one so far: http://www.jslint.com/ Thanks. Working on college assignment, cant figure it out and need help! Basically a form that asks the user to fill in a valid email and password (ill give them the password), doesnt matter if it isnt secure, or if the email accepts dodgy emails (im just verifying the @ and a . and that is ok for the purpose of this. Anyway been trying with this code for ages now and cant see what is wrong but it isnt working, ive swapped it around and at times it does check that it is a valid email, sometimes it allows empty inputs. here is the code <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["email"].value var y=document.forms["myForm"]["password"].value var atpos=x.indexOf("@"); var dotpos=x.lastIndexOf("."); if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) { alert("Not a valid e-mail address"); return false; } </script> I think i need something like && (y!="123") around the 'if' statement, but not a clue how or where it goes. Basically im going to set the password to 123 so dont have to allow for caps etc. Easiest way to do this, anyone plleeeeeaaasseee?? Kind regards Alan I'm stumped. I realise it's something basic... This works - i.e. beeps on mouseover: Code: <html> <head> <script> function EvalSound(soundobj) { var thissound= eval("document."+soundobj); thissound.Play(); } </script> </head> ... <a href="#" onMouseOver="EvalSound('sound1')">Move mouse here</a> ... <embed src="beep.mp3" autostart=false width=1 height=1 name="sound1" enablejavascript="true"> </body> </html> ...but this doesn't work: (I get the error "undefined is null or not an object") Code: <html> <head> <script> function EvalSound(soundobj) { var thissound= eval("document."+soundobj); thissound.Play(); } </script> </head> ... <script language="JavaScript"> <!-- EvalSound('sound1'); change_it1() // activates an external .js //--> </script> ... <embed src="beep.mp3" autostart=false width=1 height=1 name="sound1" enablejavascript="true"> </body> </html> What am I doing wrong? Gotta make the second idea work... Thanks Hi, im new to Js and i have this code: Code: var div = document.createElement("div"); div.id = field+count; div.name = field+count; div.class = "bubble_green"; var p = document.createElement("p"); p.appendChild(document.createTextNode('Question '+count)); div.appendChild(p); field_area.appendChild(div); assuming that the variables are all correct and working, why is only this produced: Code: <div id="question_3"><p>Question 3</p></div> instead of: Code: <div id="question_3" name="question_3" class="bubble_green"><p>Question 3</p></div> and is there a solution? I have an xml file with parts and im trying to search through the list using a javascript search script. It works fine for me but the only problem I have is that when it searches and returns something, it puts it into a table on a blank page, wiping out everything thats on there (heading, designs, etc.). How do I edit this so that it instead puts the table under the search box (where ive labeled "test" in screenshot)? Thanks in advance for the help. My java script Code: <script type="text/javascript"> function getType() { for (var i=0; i < 3; 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("wdparts.xml"); } // MSIE uses ActiveX else if (window.ActiveXObject) { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("wdparts.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('You searched for <b><i>'+searchterm+'</i></b><br><br>'); document.write('<table border="1" style="width: 100%;">'); document.write('<tr><th>Line</th><th>Product Number</th><th>Description</th><th>Link</th></tr>'); for(var i=0; i<results.length; i++) { document.write('<tr>'); document.write('<td>' + results[i].getAttribute("line") + '</td>'); document.write('<td>' + results[i].getAttribute("pnum") + '</td>'); document.write('<td>' + results[i].getAttribute("description") + '</td>'); document.write('<td>' + results[i].getAttribute("link") + '</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> <style type="text/css"> #TXT { font-size:18px; font-family:Verdana, Geneva, sans-serif; font-weight:bolder; } tblalign { text-align: center; } tblalign { text-align: center; } tbl { text-align: center; } </style> This is the search box Code: <p><form name="frmMain" id="frmMain" action=""> <b>Search: </b> <input type="radio" name="criteria" value="line" checked="checked">Line <input type="radio" name="criteria" value="pnum">Product Number <input type="radio" name="criteria" value="description">Description <br><br> <input id="searchme" type="text" size="20"> <input value="Submit" onclick="searchIndex(); return false;" type="submit"> </form></p> <p id = "test">test </p> Hi guys im new here i have a project about searching string im am going to use javascript the program should look like this. Enter first word: abcd Search in first Word: ab then pop up ab found then if i type like sdg then pop up sdg not found something like this plss how can i do that Hey guys, I know very little java I took AP computer science in high school and have since forgotten most of it. I'm trying to write a code that : What I'm trying to do is have a script that loads a website such as http://www.anywebsite.com/showthread.php?t=000001 and searches for a couple strings of words then if the strings aren't found it searches the next one, =000002, If it finds the strings that are required it would save the link or keep the page open and stop searching. I'm honestly not sure where to start so I came looking for a little bit of a shove in the right direction. Anybody with any ideas would be really appreciated. Thanks -Tim Basically what i'm trying to do is check the data in an XML node to see if it contains a certain string. I'm completely new to javascript and this seems like something very simple, but I must not be using the correct terms in my searches. For instance here i'm checking to see if the data in an xml node is equal to "URGENT" if so I'm changing the css. Code: function DoesXmlContainThisNode(strXML, strNodeXPath) { var bolFlag // Load XML var myDOMDocument = new ActiveXObject('Msxml2.DOMDocument.3.0'); myDOMDocument.async = false; myDOMDocument.loadXML(strXML); // Parse out value var myNode = myDOMDocument.selectSingleNode(strNodeXPath) if( myNode != null ) { bolFlag = true } else { bolFlag = false } myNode = null return bolFlag } , Code: if (DoesXmlContainThisNode(strResponseXml, "Response/XMLResponse/*/Message/Body[text()='URGENT']")) { strStyle = 'URGENT' } And maybe I cant do it the same way, but how would I search for any instance of the word "urgent". Say my message has 4 sentences and if the wor durgent appears anywhere in it.. I want to change the stylesheet. I would think there is some way to use a wildcard or "contains" string... I see the text() class being used everywhere but only on exact matches. Any help is greatly appreciated. Thanks Hi, I've been searching google endlessly and I've come to the conclusion I'm not using the proper search keywords. I'm trying to create something similar to the banner/button combo you can find he http://www.nba.com and also here, http://home.worldvision.org/?page=nonflash I assume these type of slide show buttons combos use java script and possibly php. If anyone knows the proper name for this type of slide show or can point me to some scripting I would appreciate it. Thanks I've tried every combination I can think of, and I can't figure this out. According to me, if you type a name that matches one of the xml items' names into the box using the following code: Code: Name: <input type="text" id="nameInput"/> <input type="button" onclick="searchLocations()" value="Search Locations"/> function searchLocations() { var input = document.getElementById('nameInput').value; if (!input) { alert("please enter a name"); } else { for (var j = 0; j < gmarkers.length; j++) { if (gmarkers[j].myname == input) { gmarkers[j].show(); } } } } it should show the gmarker with that name... but nothing. If I leave it blank and hit the search button at least I get the alert, so something is working... any suggestions? |