Solved

Search array and print results

Posted on 2009-04-13
2
404 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
2 Comments
 
LVL 9

Assisted Solution

by:Graceful_Penguin
Graceful_Penguin earned 75 total points
Comment Utility
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
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now