NEW to JavaScript and I Need help with a simple code!

This is my code below. I am trying to match the number var with the name var that is prompted in the browser… for example, if i type in Fran, i want to get Fran’s number, but no matter who’s name i put in i always get bob’s number which is the first number…what am i doing wrong??? It is a simple code, but i dont know what im doing… Thanks

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8” />
<title>Untitled Document</title>
</head>

<body>

<script type=“text/javascript”>
// Header
document.write(“<h1>Directory Lookup</h1>”);
// Variables and Arrays for names and numbers
var name = new Array();
name[0] = “Bob”;
name[1] = “Jane”;
name[2] = “Billy”;
name[3] = “Fran”;
name[4] = “Rex”;
var number = new Array();
number[0] = “555-308-1232”;
number[1] = “453-346-3299”;
number[2] = “219-233-9832”;
number[3] = “453-282-7628”;
number[4] = “324-339-1193”;

// Variable for name propmt
var nameS = prompt(“Enter the name you are looking for!”,“Enter Here”);

var count = 0;
for (count in name)
{
if (name[count] == nameS);
}

// Alert pop up with name and number
alert(nameS + number[count]);
// What appears in HTML browser
document.write(“<p>” + nameS + number[count] + “</p>”);

</script>

</body>
</html>

i tried everything, i even did it exactly how you guys did it and nothing. all i get is a blank screen… either i’m retarded, or my computer doesn’t like me…

<script type=“text/javascript”>
// Header
document.write(“<h1>Directory Lookup</h1>”);
// Variables and Arrays for names and numbers
var name = new Array();
name[0] = “Bob”;
name[1] = “Jane”;
name[2] = “Billy”;
name[3] = “Fran”;
name[4] = “Rex”;
var number = new Array();
number[0] = “555-308-1232”;
number[1] = “453-346-3299”;
number[2] = “219-233-9832”;
number[3] = “453-282-7628”;
number[4] = “324-339-1193”;

// Variable for name propmt
var nameS = prompt(“Enter the name you are looking for!”,“Enter Here”);

var count = 0;
for (count in name)
{
if(name[count] == nameS) {
// Alert pop up with name and number
alert(nameS + number[count]);
// What appears in HTML browser
document.write(nameS + number[count]); // <---- i even removed the <p> to see if it would work without it

}

}

</script>

your code works ok in my browser.

look at my code, it seems you did not check what I wrote.

You use this :
if (name[count] == nameS);

this will not execute that if code, so you have to make it like this

if (name[count] == nameS)
{
// alert code goes here.

}

No, it’s not your browser.

My original suggestion was to include the ‘display’ code within your IF block.

You haven’t included the ‘display’ code in your IF block properly. Code within IF blocks needs to be enclosed within a pair of {}

Your IF block should be

 
for (count in name) 
{ 
    if (name[count] == nameS) [B][COLOR=red]{[/COLOR][/B]
         // Alert pop up with name and number
         alert(nameS + number[count]);
         // What appears in HTML browser
         document.write("<p>" + nameS + number[count] + "</p>");
     [B][COLOR=red]}[/COLOR][/B]
}

Note the red {}

A tutorial on IF blocks

post your updated code and we can have a look at it.

putting your “display” code inside the IF block worked in my browser.

maybe you still have some logic or syntax errors.

if you post your updated code it will be easier to guide you.

This is what i have so far… could it be my browser? im using chrome.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=UTF-8” />
<title>Untitled Document</title>
</head>

<body>

<script type=“text/javascript”>
// Header
document.write(“<h1>Directory Lookup</h1>”);
// Variables and Arrays for names and numbers
var name = new Array();
name[0] = “Bob”;
name[1] = “Jane”;
name[2] = “Billy”;
name[3] = “Fran”;
name[4] = “Rex”;
var number = new Array();
number[0] = “555-308-1232”;
number[1] = “453-346-3299”;
number[2] = “219-233-9832”;
number[3] = “453-282-7628”;
number[4] = “324-339-1193”;

// Variable for name propmt
var nameS = prompt(“Enter the name you are looking for!”,“Enter Here”);

var count = 0;
for (count in name)
{
if (name[count] == nameS);
// Alert pop up with name and number
alert(nameS + number[count]);
// What appears in HTML browser
document.write(“<p>” + nameS + number[count] + “</p>”);

}

</script>

</body>
</html>

thanks a lot! i appreciate all the help…

Hi

Put alert & document.write code in side the if() instead of out side the loop.


var count = 0;
for (count in name)
{
	if(name[count] == nameS)
	{
		// Alert pop up with name and number
		alert(nameS + number[count]);
		// What appears in HTML browser
		document.write("<p>" + nameS + number[count] + "</p>");	
	}
}

either i’m retarded, or my computer doesn’t like me…

Take a deep breath.

Read this: http://writing.bryanwoods4e.com/1-poor-poor-child

I’m only a little ahead of you in this learning of Javascript, but every word above rings true.

Also, use a debugger. Chrome has a debugger which soon will do some things Firebug can’t; otherwise check your code running with Firebug in Firefox. I learned how to us Firebug very basically with Kevin Yank’s Javascript Live course but it’s also documented all over the web (Chrome’s prolly is too but keep updating your Chrome 'cause I heard Paul Irish say its debugger was going to get super awesome sometime soon). Once you see how the browser steps through your code, it suddenly shows you what’s going on and you can “see” what it’s doing. Breakpoints ++

Using a debugger AND running your Javascript through JSLint.com will help you find when your code is either total crap or just not working because of some typo syntax error. Both these things will help you in school and aren’t cheating. You are clearly still learning syntax. Let your browser tell you that you have a syntax error: it’ll even tell you what line (or very close) the error is on. This is awesome.

Instead of Kalon’s solution, I had been considering just an object with key-value pairs, instead of a two-dimensional array, so anyway I hope your teacher gets into those soon because both are pretty cool. Wish I had a teacher in a class teaching me Javascript, so long as s/he didn’t suck teaching.

ok, since this is for your class homework I won’t post the actual code but all you need to do to fix your original code is put your code to alert() and display the name and number on the page inside your IF block where you compare the name entered by the user to the values in the name array.

thats awesome!!! thanks a lot, it works perfect, but its for my Intro to JavaScript class and if i use this code my teacher will know i didnt do it… is there a way to write this script in a more simple way sort of like i have in th original… what am i missing from the original code to make it work the right way… thanks a lot for the help… i really appreciate it…

Yes… Kalon told me to do that, but its not working for some reason. this stuff is so confusing… i appreciate the help though…

You have logic errors in your code.

I would do it this way.

 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<style type="text/css">
#result {
 display: none
}
</style>
<script type="text/javascript">
 
// set up phone book
var phoneBook = [["bob","555-308-1232"],
                          ["jane","453-346-3299"],
                          ["billy","219-233-9832"],
                          ["fran","453-282-7628"],
                          ["rex","324-339-1193"]
                          ];
 
window.onload=function() {
     var nameS = prompt("Enter the name you are looking for!","Enter Here").toLowerCase();
 
    //get the phone number for nameS
    for(var i=0; i < phoneBook.length; i++) {
     if(phoneBook[i][0] == nameS) { //found the name in the phone book
            document.getElementById("spName").innerHTML = nameS;
            document.getElementById("spNo").innerHTML = phoneBook[i][1];
            document.getElementById("result").style.display = 'block';
            i = phoneBook.length;
        }
    }
}
</script>
</head>
<body>
 
<h1>Directory Lookup</h1>
 
<p id="result">Phone number for <span id="spName"></span> is <span id="spNo"></span></p>
 
</body>
</html>

Much like Stommie, I’m learning or after six months out re-learning.

Good advice about using something like firebug. The console.log command comes in very handy when trying to debug.

I know you want to keep things simple, but I have experimented a bit with your code.

  1. I’ve used a simple regular expression to convert the first letter of the input to uppercase. So ‘billy’ will work as well as ‘Billy’. Regular expressions albeit a bit daunting at first, are certainly worth looking into for these type of form input exercises. They get a bit addictive once you get into them:)

  2. I’ve written a poorman’s indexOf function (arrayIndexOf). You can do a google for ‘javascript array indexof’ for more on it. It checks an array for a match. If a match is found it returns the index number so for instance Fran returns 3 and if no match it returns -1. You could use this function to check the numbers instead and match it to a name.

As I say just experimenting:D

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Number Check</title>
</head>
<body>

<script type="text/javascript">
// Header
document.write("<h1>Directory Lookup</h1>");
// Variables and Arrays for names and numbers
var names = []; // shorthand for new Array;
names[0] = "Bob";
names[1] = "Jane";
names[2] = "Billy";
names[3] = "Fran";
names[4] = "Rex";

var numbers = [];
numbers[0] = "555-308-1232";
numbers[1] = "453-346-3299";
numbers[2] = "219-233-9832";
numbers[3] = "453-282-7628";
numbers[4] = "324-339-1193";

// Variable for name prompt

// Using a regular expression we can match the first letter and replace it with it's upper case equivalent.
// i.e. if you accidentally input 'billy' it will still match to 'Billy'
// regexp code: ^ = beginning of input. \\w = a letter.
// 'x' is the match (in this case the first letter)
// return x.toUpperCase() converts match 'x' to upper case then return the whole string i.e. 'Billy'.
// A list of regular expression codes can be found here http://www.javascriptkit.com/javatutors/redev2.shtml

var nameInput = prompt("Enter the name you are looking for!","Enter Here").replace(/^\\w/, function (x){return x.toUpperCase()});;

var count = 0;

// a function to check our array for a match and return an index of that match
// if no match it returns -1;
// so for instance if nameInput is 'Jane'. arrayIndexOf( names, nameInput )
// should return 1. if 'Fred' -1.
// we could also maybe use it the other way to find a name by entering 291-233-9832. arrayIndexOf (numbers, numberInput);

function arrayIndexOf(array2Check, nameInput) {
	// check array2Check is in fact an Array with 'instanceof Array' and that there is a nameInput argument.
	// if so perform our loop within the if statement block.
	// if not then jump to the else statement block and throw an error.
	if (array2Check instanceof Array && arguments[1]) {
		// arrLen is the length of the array2Check.
		var arrLen = array2Check.length;
		// Loop through our array. 'i' is our counter.
		for (var i = 0; i < arrLen ; i++){
			if (array2Check[i] == nameInput) { 
				return i; // return the index with which we found a match
			}			
		}
		// we have got to the end of the loop without returning so no match. return false
		return -1;
	} else { 
		throw new Error("Error: arrayIndexOf() expects 2 arguments. An array and a valid input.");
	}
}

var checkName = arrayIndexOf(names, nameInput); // call the arrayIndexOf function and store the return value in checkName.
if (checkName == -1) {
	alert ("No match sorry!");
} else {
	alert (nameInput +' : '+ numbers[checkName]);
	document.write (nameInput +' : '+ numbers[checkName]);
}
</script>
</body>
</html>

RLM

Frustrating not being able to go back and edit posts. Just looked at Chrome’s web developer tool and it looks to be very good. Liking the console a lot:D

Paul Irish gave a little lightning talk in a bar in Amsterdam where he showed a few things they wanted to do:

-let Chrome dev box dock and undock like Firebug
-separate a selected DOM element and show local styles and events on it (Firebug doesn’t do quite what he described yet, but if Chrome does it Firebug surely will follow… sounded nice)
-better event following and monitoring blocking I think