Solved

Search array and print results

Posted on 2009-04-13
2
432 Views
Last Modified: 2012-05-06
I am writing a javascript program that allows the user to enter the names and email addresses of various people (which are stored in an array) and also search the array (using something like indexOf() I assume) for strings matching the search in the name or email input and printing out the name and email of each person it finds.

I'm having trouble getting the search function to work. I've tried looping through the array to match the search input and send that to another array which will be printed out but I never end up with the desired results. Any help would be greatly appreciated.

Here's my code so far:


<html>
<head>
	<title>String Manipulation</title>
 
<script language = "JavaScript">
 
 
 
	var index = 0;
	var people = new Array();
 
 
	function addPerson()
	{
 
		var myRegExp = /[^a-z\d-_.@]/g;
 
		var name = document.form.name.value;
		var email = document.form.email.value;
 
	//	nwsName = name.replace(" ", "");
	//	nwsEmail = email.replace(" ", "");
 
	    nameCheck = document.getElementById("name");
	    emailCheck = document.getElementById("email");
 
		printOut = document.getElementById("printout");
 
 
		if(name.length == 0)
		{
			nameCheck.innerHTML = "Please enter a name";
		}
 
		else
		{
			nameCheck.innerHTML = "";
		}
 
 
 
		if(email.length == 0)
		{
			emailCheck.innerHTML = "Please enter an email";
		}
 
 
		else if(email.length < 7)
		{
			emailCheck.innerHTML = "Email must have at least 7 characters";
		}
 
 
	    else if(myRegExp.test(email))
		{
			emailCheck.innerHTML = "Only valid characters are letters, numbers, ampersand ( @ ), hyphen ( - ), \
			underscore (  _  ), and period ( . )";
		}
 
 
		else if(email.indexOf("@") == -1)
		{
			emailCheck.innerHTML = "Email must have an @ in it";
		}
 
 
		else if(email.indexOf(".") == -1)
		{
			emailCheck.innerHTML = "Email must have a period (.) in it";
		}
 
		else if(name.length > 0)
		{
			emailCheck.innerHTML = "";
 
			printOut.innerHTML = ("<font color=009900>" + name + ", " + email + " </font> has been added to the array");
 
			people[index] = (name + ", " + email);
			index++;
		}
	}
 
 
 
	function searchArray()
	{
		/* 
		tried various methods here and couldn't get any to work  
		*/
		   
	}
 
 
 
	function resetEntries()
	{
		nameCheck.innerHTML = "";
		emailCheck.innerHTML = "";
		printOut.innerHTML = "";
	}
 
 
</script>
 
 
</head>
<body bgcolor="#c0c0c0">
<h1>String Manipulation Assignment</h1>
<h2>Search/Add Students</h2>
 
<form name="form">
 
<table>
 
<td>Name
<td><input type="text" name="name"> <font color="ff0000"  id="name"></font><br>
<tr>
<td>Email
<td><input type="text" name="email"><font color="ff0000"  id="email"></font>
 
</table>
 
<br><br>
 
<input type="button" value="Search" onclick = searchArray()>
<input type="button" value="Add" onclick = addPerson()>
<input type="reset" name="myReset" value="Reset" onclick = resetEntries()>
 
<br><br>
 
<p>Results:</p>
 
<div id="printout"></div>
 
</form>
</html>

Open in new window

0
Comment
Question by:johnjmk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 9

Assisted Solution

by:Graceful_Penguin
Graceful_Penguin earned 75 total points
ID: 24135837
Try the code below. BTW if i did this I would not concatenate the name and email I would rather use a two dimensonal array or better yet use the name as the index. Then I can search very easly with a small change to the code that I gave you
function searchArray(testString)
{
  var matches = new Array();
  var matchCount = 0;
  for (key in people)
  {
    if (people[key].indexOf(testString) > 0)
    {
      matches[matchCount] = people[key];
      matchCount++;
    }
  }
}

Open in new window

0
 
LVL 14

Accepted Solution

by:
sam2912 earned 425 total points
ID: 24141515
Use this
<html>
<head>
<title>String Manipulation</title>
<script type="text/javascript">
var people = new Array;
 
function addPerson() {
	var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var nameCheck  = document.getElementById("nameCheck");
	var emailCheck = document.getElementById("emailCheck");
	var printOut   = document.getElementById("printOut");
	var resultArea = document.getElementById("resultArea");
	var name  = document.form.name.value;
	var email = document.form.email.value;
	var validName = false, validEmail = false;
	
	resetEntries();
	
	// Check name
	if (name.length == 0) {
		nameCheck.innerHTML = " * Please enter a name";
	}
	else {
		validName = true;
		nameCheck.innerHTML = "";
	}
	
	// Check email
	if (email.length == 0) {
		emailCheck.innerHTML = " * Please enter an email";
	}
	else if (email.length < 7) {
		emailCheck.innerHTML = " * Email must have at least 7 characters";
	}
	else if (!emailFilter.test(email)) {
		emailCheck.innerHTML = " * Email is not in a valid format";
	}
	else {
		validEmail = true;
		emailCheck.innerHTML = "";
	}
	
	if(validName && validEmail) {
		people.push(name + ", " + email);
		document.form.reset();
		printOut.innerHTML = "<font color='009900'>" + name + ", " + email + " </font> has been added to the array.";
	}
}
 
 
function doSearch(mode) { // mode=1 to show all
	resetEntries();
	var results = new Array;
	var string  = document.searchform.query.value;
	var theResults = document.getElementById("theResults");
	
	theResults.innerHTML = "";
	if(mode==1) string=" ";
	
	for(i=0;i<people.length;i++) {
		if(people[i].indexOf(string) > 0) {
			results.push(people[i]);
		}
	}
	
	if(results.length>0) {
		var html = "<ol>";
		for(i=0;i<results.length;i++) {
			html+="<li>"+results[i]+"</li>";
		}
		theResults.innerHTML = html + "</ol>";
	}
	
	theResults.innerHTML += "There are "+results.length+" results.";
	document.getElementById("resultArea").style.display="inline";
}
 
 
 // Resets all error messages
function resetEntries() {
	nameCheck.innerHTML  = "";
	emailCheck.innerHTML = "";
	printOut.innerHTML   = "";
}
 
function resetSearch() {
	document.getElementById("resultArea").style.display="none";
}
</script>
<style type="text/css">
.error {
	color:red;
}
h1 {
	font-size:26px;
}
h2 {
	font-size:20px;
	margin-bottom:0px;
	padding-bottom:0px;
}
</style>
</head>
<body bgcolor="#c0c0c0">
<h1>String Manipulation Assignment</h1>
<h2>Add Students</h2>
<form name="form">
  <table>
    <tr>
      <td width="70">Name:</td>
      <td><input type="text" name="name" value="" size="30" />
        <span id="nameCheck" class="error"></span></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><input type="text" name="email" value="" size="30" />
        <span id="emailCheck" class="error"></span></td>
    </tr>
  </table>
  <div id="printOut"></div>
  <input type="button" value="Add" onclick="addPerson();" />
  <input type="reset" value="Reset" onclick="resetEntries();" />
</form>
<hr />
<h2>Search</h2>
<form name="searchform">
  <input type="text" name="query" value="" size="30" />
  <input type="button" value="Search" onclick="doSearch(0);" />
  <input type="button" value="Show All" onclick="doSearch(1);" />
  <input type="reset" value="Clear" onclick="resetSearch();" />
</form>
<div id="resultArea" style="display:none; padding:0px;">
  <p style="font-weight:bold; text-decoration:underline;">Results:</p>
  <div id="theResults" style="padding-left:10px; padding-top:0px;"></div> </div>
</body>
</html>

Open in new window

0

Featured Post

Tutorials alone can't teach real engineering

So we built better training tools.

-Hands-on Labs
-Instructor Mentoring
-Scenario-Based Tests
-Dedicated Cloud Servers

All at your fingertips. What are you waiting for?

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

724 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question