JavaScript - Searching Through An Array
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. 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, 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 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? 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. 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? 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 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> 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? 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. 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 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 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 Hey all, I'm a total newbie in the JavaScript programming field, so please bear with me if I ask any ridiculously simple questions I am trying to make a study site for my university study group. What I'm trying to do is this: For a search term (say "Differential Equations"), find all pages in Wikipedia that match this term. Then, download all pages to local drive so that I and my friends can go over it later offline... (our study group does not have uninterrupted access to the internet). I tried this simple JavaScript code to get the searches: <html> <head> <script type="text/javascript"> function getpages() { var frm = document.getElementById("GetPages"); frm.submit(); } window.onload = getpages; </script> </head> <body> <center> <FORM method=GET action="http://www.google.com/search" name = "GetPages" id="GetPages"> <TABLE bgcolor="#FFFFFF"><tr><td> <INPUT TYPE=text name=q size=31 maxlength=255 value="site:wikipedia.org/ differential equations"> <INPUT TYPE=hidden name=hl value="en"> </td></tr></TABLE> </FORM> </center> </body> </html> It gives me the expected results. However, I'm not sure how to download the pages that the search returns. Also, Google returns only 10 search results per page by default - it would be nice to work around both these problems. 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 Hi I have the following JavaScript search text box on my Google map page: which searches for locations on the map: Code: <input type="text" id="postcode" size="28" /> <input style="height:23px" type="submit" class="button" value="center map" onclick="javascript:usePointFromPostcode(document.getElementById('postcode').value, placeMarkerAtPoint)" /> Is it possible to adapt this code so it can be put on a separate page, so the user can search my map? Any help will be much appreciated Thanks in advance Rifki hey guys i have the following code that extracts the information from the questiondiv then i have a for loop to search the array but it keeps returning it has no answer can someone help me please and i know im most probly doing somthing realy silly wrong. P.S some reason the codes indenting got messed up when i pasted it here Code: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> function code() { function getNodes(prop, val, meth, nd, useSelf ) { var r=[], any= getNodes[val]===true; nd=nd||document.documentElement; if(nd.constructor===Array){nd={childNodes:nd};} for(var cn=nd.childNodes, i=0, mx=cn.length;i<mx;i++) { var it=cn[i]; if( it.childNodes.length && !useSelf ){r=r.concat(getNodes(prop, val, meth, it,useSelf ));} if( any ? it[prop] : (it[prop]!==undefined && (meth ? ""[meth] && String(it[prop])[meth](val) : it[prop]==val))){ r[r.length]=it; } }//nxt return r; };getNodes[null]=true;getNodes[undefined]=true; //end getNodes() var answer; trivia = new Array('test?','test1'); var triviaGet = getNodes( "data", //examine each node's .data property (only hits text nodes) /\?/, //looking for text with a "?" "match", //using String().match method to accept arguments[1] document.getElementById("questiondiv") // looking in the question div )[0].textContent.split("?")[0]+"?" //show text of first match alert(triviaGet); var i=0; var answer1; var answer2; for(i=0; i < 8400; i++) { if(trivia[i] == triviaGet) { answer = trivia[i]+1; document.getElementById("test").innerHTML=(answer) break; } else { document.getElementById("test").innerHTML=("Answer not found!"); } } //search trivia array for match to question //when found the answer is the next one in the array so if it finds the question at index 7261 then the answer is in index 7262 // TODO: insert answer into text box... } </script> </head> <body> <div style="display: none;" id="questiondiv"> You challenge The Wiseman to a game of trivia, he asks you this question:<br/> <br/> test?<br/> <br/> <input class="dungeoninput" type="text" size="16" id="answer" value="" maxlength="32"></input><br/> <div class="btn100" style="margin-top: 6px;" onclick="loadDiv2('/dream/explore?action=acceptTrivia&qid=727'); return false;">Answer</div> </div> <div id="test"> test </div><br /> <button value="code()" onclick="code()">click me</button> </body></html> Hi all - I'm designing a website, and I need to have a search button allow users to search the inventory that is on the website. I'm not quite sure what code I'm going to use for the search button, but I imagine that I can work on that sometime.. Along with the code, am I required to have something such as a MySQL database set-up or something of the sort? This question may be mis-categorized, so please let me know if it is. Thanks everyone! If in my page I have a facebook widget & a pagecounter widget, both I dont want to display on pages other than homepage. I will do 1] Code: <div id="facebook"> .....facebookwidget...</div> <div id="counter">.....counterwidget.....</div> then I will use something like this 2] Code: $(function() { var currentUrl = window.location.href; if(currentUrl != 'http://engineering.forumotion.info/') { $('#facebook').remove(); $('#counter').remove(); } }); However if I use a same id for both widgets say e.g facebook then Code: $(function() { var currentUrl = window.location.href; if(currentUrl != 'http://engineering.forumotion.info/') { $('#facebook').remove(); } }); the above code only removes one(that occurs first) widget & NOT the other widget with the same id. Here we include looping, plz anyone tell me how one start & end a loop, to find a particular class/ID. Plus how the jquery .each() function can be implemented Hi they all, I want make autocompleted searching for my site. I find HTML5 autocompleted script in google. I use Laravel and PHP and MongoDB. My script PHP Code for search autocompleted. PHP Code: publicfunction searchAutoCompleteAjax(){ $keyword =Input::get('keyword'); $result = array();if(!empty(trim($keyword))){ $mongoResult =MongoDB::instance(true)->collection("items")->like('name',$keyword)->limit(0,10)->fetch(); if($mongoResult){foreach($mongoResult as $key => $item){ $result[]= $item['name'];}}} echo json_encode(array("error"=>0,"message"=>"Success","result"=>$result));} I result 10 query PHP Code: $mongoResult =MongoDB::instance(true)->collection("items")->like('name',$keyword)->limit(0,10)->fetch(); My old javascript code and working for me. Im trying to use javascript to search a text file. text file is like this... 1111111[TAB]Project Name[TAB]Application1 2222222[TAB]Project Name[TAB]Application2 Im trying to get the javascript to let a user search for number or project name, if found it displays all the info if found. application1 or application2 (whatever is in the 3rd area) The text file can also be seperated by commas, either way is fine. can anyone help with this. ? |