PDA

View Full Version : Requesting Help for beginner Jscript



ShadowBoss
Apr 5th, 2012, 03:56 AM
hi folks extreme newbie here when it comes to javascript.

I have an assignment that in which ive created the html+css for the webpage (a pizza form validation basically).

and Now I must do the javascript aspect of it. Unfortunately I have no idea how to even begin i dont understand how to use any of these .toUpperCase() .toLowerCase(), how to use window.open for errors instead of alert and all these other things.


the way i'm coding it, is with an external file called script.js that will have all my coding and then i have my index.html file...i dont know how to 'call' (if thats the right term) the function to the index.html...or even make jscript code either lol.

as an example of a requirement:



field01 - Client Surname-
Maximum allowable length is 15 positions
Must be present.

Minimum of four (4) alphabetic characters
lower case (a-z) or upper case (A-Z) or a mix of lower & upper case.

Optional special characters

Optional one (1) apostrophe
if present - must have at least 1 alphabetic character before it and one alphabetic character after it.

Optional one (1) hyphen
if present - must have at least 1 alphabetic character before it and one alphabetic character after it.


this is my assignment requirements for those need a better understanding of what's going on
https://cs.senecac.on.ca/~int222/assignments/121/assignment3-2/


my request is if there is anyone who can lead me in the direction to a website or downloadable book on how to do what it's asking (in no way am i asking someone to do my assignment for me).

My professor has his website that has all these predefined things (im assuming are functions) that should be used but i dont understand it nor do i understand him.

Any help would be immensely appreciated, thank you.

Mishu
Apr 5th, 2012, 04:07 AM
and Now I must do the javascript aspect of it. Unfortunately I have no idea how to even begin i dont understand how to use any of these .toUpperCase() .toLowerCase(), how to use window.open for errors instead of alert and all these other things.


How come you have no idea? Have you not been attending classes (online or whatever) and not been doing any course work before you were given this assignment?



I have an assignment that in which ive created the html+css for the webpage (a pizza form validation basically).


Oh no!!!!! not another pizza form :(:eek::D

But I digress...sorry :o

Post the javascript you have so far and we can try to steer you to get it working. Doing other peoples's homework is not against the rules but it is frowned upon.


1.5) No homework assignments - Do not post your entire homework assignment and request that other members do it for you. This is considered cheating, and your thread may even be used by your school to prove your guilt. Now, you may ask for advice or help on a specific aspect of your assignment that you're having trouble with. Use common sense as far as what's acceptable in terms of soliciting help with homework assignments.

ShadowBoss
Apr 5th, 2012, 05:05 AM
I have been attending class but I don't understand what he's doing. I tried to get in with a tutor on campus but their booked by a bunch of other folks from my class lol.


that's the problem though, I don't have anything because I don't know where to start or even how to start.


all i've got is



function PizzaFormValidation()
{
var error = "";
var content = "";

errMessages = validatefield01(errMessages); // Call field one validation
errMessages = validatefield02(errMessages); // Call field two validation



if (errMessages != "") {

content=pageHeader(field01);
content += errMessages;
content=pageFooter(field01);


content=window.open("","errors","");

content.document.write(content);
content.document.close();


content.window.focus();

return false;

}
else {
return true;
}


}

and then all my functions are suppose to go within that main function.

what i did there I'm not even sure if it's right...nothing seems to work but then I don't have anything validating the fields lol.

and this assignment is actually the only course work...he released 1 lab for javascript and I tried to do that but couldn't and then he dropped the assignment on us.

here is what we'd be looking at (sorry i can't actually give the link to my page its under password protection from the college and if i allow access i get kicked out)

http://postimage.org/image/3x0hevcuv/
http://postimage.org/image/3x0hevcuv/

Old Pedant
Apr 5th, 2012, 08:40 AM
Were you given the code you showed us, or did you create that on your own??

It seems a strange way to validate a <form> though it could be done basically that way (I wouldn't). But even as written it has errors.

Where are the functions that you are using there? You don't show them:
validateField01
validateField02
pageHeader
pageFooter

Where is the definition of the variable
field01
???

Aside from the above, your main code is badly broken:


if (errMessages != "") {

content=pageHeader(field01);
content += errMessages;
content=pageFooter(field01); // this line just WIPED OUT the prior value of content variable

content=window.open("","errors",""); // and this line wipes it out again!

content.document.write(content); // here, content is a reference to the window you opened
// so you can't document.write the window reference!
content.document.close();


content.window.focus(); // content *IS* a window, so content.window is meaningless

return false;

}

I *suspect* you mean to do:


if (errMessages != "") {

content=pageHeader(field01);
content += errMessages;
content += pageFooter(field01); // ADD to the conten!


var popup = window.open("","errors",""); // use a DIFFERENT variable

popup.document.write(content);
popup.document.close();

popup.focus();

return false;

}

But I don't understand why you don't simply do


if (errMessages != "") {
alert("Errorr(s): " + errMessages);
return false;
}

Surely that is more than enough for a beginner level class.

Old Pedant
Apr 5th, 2012, 08:45 AM
As for calling the function:


<form name="doNotNeedOneButOkay" id="ditto" onsubmit="return PizzaFormValidation(this);">

and then start the validation function with

function PizzaFormValidation( form )
{
// and now you can reference form fields by name in here using that reference
var surname = form.Surname.value; // example only
...

ShadowBoss
Apr 5th, 2012, 03:38 PM
the only code that was given to us was the calculation functions for the pizza toppings which we are not allowed to touch.

the code i wrote there was based off some notes that i took which i'm guessing were taken wrong (as i said i didn't understand his lectures on java) so I asked the professor and he says what I wrote down was his example but his example didn't provide his javascript functions so my notes were 'incomplete'.


I wish i could use alert however the professor doesn't want us using alert he want's us to use a pop up window so that the 'client' could look at the errors they made and fix them because once you press 'ok' the alert is gone as professor says. So I don't have a choice I must use window.open to display my errors...

So to use the window.open its better to assign a different variable ? i'll keep that in mind thank you.

The intention for this pop up window is to display the errors i have for all fields such as the Client Surname/Phone Number/Date of Birth/selecting a size, crust, and topping/ so that when the user click's submit it wont submit the form until the requirements are filled out.

On top of that I need to figure out how to validate user inputs into the fields

for example client surname can only have minimum 4 characters no spaces up to 15 characters and when they click submit on the forum the client name turns automatically to caps (but it can have ' and -, and it must have a character on both sides )

ie. s'hadow (click submit) = S'HADOW

now say i have "field01" as a variable for the string to represent the actual field01 in the html form,


field01= field01.substring(0,16) + field01.toUppercase(0);

or would it be


field01 = field01.substring(0,16).toUpperCase(0)

would that make whatever the user inputs uppercase when they submit the form?

and would (0,16) make it maximum of 15 positions? because it reads everything upto and before 16th position?

I have no idea how to apply the character before and after the ' or - especially because he never told us how he said "figure it out" ...so yeah.

xelawho
Apr 5th, 2012, 04:37 PM
wow. sounds like he really threw you under a bus.

We could answer specific questions all day, but that would take forever and you probably won't end up learning much. You really need to be able to test things for yourself, and the best way to do that I think for you at this point is to take each component of the assignment and figure it out step by step.

So make a separate document and create on function at a time. Once you have it working move on to the next one. Here's an example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
<form name="myform">
<input type="text" name="testbox"/>
<input type="button" value="test" onclick="test()"/>
</form>
<div id="results"></div>
<script type = "text/javascript">
function test(){
str = document.myform.testbox.value.substring(0,16).toUpperCase();
document.getElementById("results").innerHTML=str;
}
</script>
</body>
</html>


you will also need to learn to use a debugger - Chrome has a good one that you can access via the spanner (top right)>tools> javascript console. Some people like the firebug plug in for firefox. Any browser but IE has a decent debugger either built in or as a plugin. If something is not working the way you want it to, your first move should be to check the error console.

there are a multitude of built-in methods for when you are dealing with strings (as you are with text inputs) have a look here (http://www.w3schools.com/jsref/jsref_obj_string.asp) for a decent explanation of them. bear in mind that you can chain methods, as you did in your example (and I copied above) with substring() and toUppercase()

for your apostrophe comma problem, I would suggest having a look at the replace() method

good luck.

ShadowBoss
Apr 5th, 2012, 05:01 PM
wow. sounds like he really threw you under a bus.

We could answer specific questions all day, but that would take forever and you probably won't end up learning much. You really need to be able to test things for yourself, and the best way to do that I think for you at this point is to take each component of the assignment and figure it out step by step.

So make a separate document and create on function at a time. Once you have it working move on to the next one. Here's an example:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
<form name="myform">
<input type="text" name="testbox"/>
<input type="button" value="test" onclick="test()"/>
</form>
<div id="results"></div>
<script type = "text/javascript">
function test(){
str = document.myform.testbox.value.substring(0,16).toUpperCase();
document.getElementById("results").innerHTML=str;
}
</script>
</body>
</html>


you will also need to learn to use a debugger - Chrome has a good one that you can access via the spanner (top right)>tools> javascript console. Some people like the firebug plug in for firefox. Any browser but IE has a decent debugger either built in or as a plugin. If something is not working the way you want it to, your first move should be to check the error console.

there are a multitude of built-in methods for when you are dealing with strings (as you are with text inputs) have a look here (http://www.w3schools.com/jsref/jsref_obj_string.asp) for a decent explanation of them. bear in mind that you can chain methods, as you did in your example (and I copied above) with substring() and toUppercase()

for your apostrophe comma problem, I would suggest having a look at the replace() method

good luck.


that's an excellent idea, thank you very much Xelawho.

in your example ' str ' would be your global variable right?

xelawho
Apr 5th, 2012, 05:11 PM
once you have run the test function (and so defined the variable) you can type the variable name into the javascript console. if you get the variable value back, it is global. if it comes back undefined it is local

Old Pedant
Apr 5th, 2012, 08:52 PM
Let's at least tell you that taking the substring of a string *DOES NOT* in any way limiit the size of the original string.

To *check* the size of the string, just use the .length property.

e.g.,


var test = "Now is the time for all good men to come to!";
alert( test.length );

ShadowBoss
Apr 5th, 2012, 09:29 PM
function validatefield01(errMessages) {
var entry1_info = document.pizza.field01.value; // Get the content of fieldOne

if ((entry1_info.length == 0){
errMessages += " <li>Minimum characters for Client Surname is 4 maximum 15\n";
errMessages += " must use characters only, Apostrophe ( ' ) or hyphen (-) is acceptable.</li>\n";
}

else if ((entry1_info.length <4) && (entry1_info.length <15)) {
errMessages += " <li>Minimum characters for Client Surname is 4 maximum 15\n";
errMessages += " must use characters only, Apostrophe ( ' ) or hyphen (-) is acceptable.</li>\n";
}


so that's what i've done so far for checking the client surname for length and validity (thank you Old Pendant) for the .length.

I don't know how i would check to make sure that the user only uses characters and not numbers :/...im thinking of using the ASCII table but I don't know how I'd implement that...

xelawho
Apr 5th, 2012, 09:44 PM
I would suggest googling javascript regex before going further down the ascii table path.

or maybe even just form validation in general - there's a ton/tonne of examples out there for you to look at

Old Pedant
Apr 5th, 2012, 09:53 PM
Good start, but overly complex. Why test for 0 length separately? The test for < 4 will automatically test for 0.



function validatefield01(errMessages) {
var entry1_info = document.pizza.field01.value; // Get the content of fieldOne

if ((entry1_info.length <4) || (entry1_info.length >15)) {
errMessages += " <li>Minimum characters for Client Surname is 4 maximum 15\n";
errMessages += " must use characters only, Apostrophe ( ' ) or hyphen (-) is acceptable.</li>\n";
}
}

But not close to complete.

First of all, I think if you re-read the task, you will see that it does *NOT* say "use characters only" but instead says "use letters only".

In any case, you have no check for apostrophe or hypen in there, at all.

HINT: You almost surely should be using a regular expression here.

Old Pedant
Apr 5th, 2012, 09:55 PM
And there really is no reason to PASS IN the current set of error messages.

Just return your message and use

errorMessages += validatefield01( );

Old Pedant
Apr 5th, 2012, 10:00 PM
Try this regular expression:


/^[a-z]+[\-\']?[a-z]+$/i

That reads as:
^ == beginning of text
[a-z] == a letter
[a-z]+ == one OR MORE letters
[\-\']? == OPTIONAL hyphen or apostrophe
[a-z]+ == one OR MORE letters
$ == end of text
/i == ignore case (upper or lower mixed okay)

Add that to checking for length and you are good to go.

But YOU need to read up and find out how to use that regexp.

felgall
Apr 5th, 2012, 10:33 PM
Any browser but IE has a decent debugger either built in or as a plugin.

Untrue - Chrome, Safari, Opera, and IE8+ all have basically the same debugger built in.

You can get the same debugger for Firefox - it is called Venkmann

You can also get the same debugger for eariler versions of IE if you install the Developer Toolbar.

So IE isn't the exception - Firefox is (because its debugger doesn't come built in).

ShadowBoss
Apr 5th, 2012, 11:49 PM
oh sorry I forgot to mention that we're not allowed to use regular expressions at all for this assignment (apparently to learn how to code in javascript, regular expressions wont help you learn..lol..)

the apostrophe and hyphen I'm still working on trying to figure out how to use it.

i think a for loop would work, I'm reading up on charAt(n) was told that might help me.

I managed to get the toppings and size to work (the hardpart was already done i just had to add the call to the toppings etc).

So I'm only left with the first few fields so I am making progress thanks to you all, so I really do appreciate this.

Old Pedant
Apr 6th, 2012, 12:14 AM
i think a for loop would work, I'm reading up on charAt(n) was told that might help me.

Yes, that's probably best choice when you can't use regexp's.

Let me give you one hint: To ensure that there is a letter both before and after the hyphen or apostrophe, simply make sure there is a letter as both the first and last character of the string. And then simply count the occurrences of hyphen/apostrophe and choke if it's more than 1.

ShadowBoss
Apr 7th, 2012, 09:04 AM
I thought It'd be respectful to update you guys and let you know I'm half way there.

Old Pendant, that was a good hint thank's to pointing me in the right direction folks, I've managed to apply various parts of field01 into field02 and im sure i can in field03.

The code is a little messy I'm sure I could clean it up a lot and make it more simpler and compact but for now it works without errors lol.

Thanks again.

ShadowBoss
Apr 8th, 2012, 08:13 AM
hey guys...I need your help again.

I'm trying to figure out the final piece to my assignment.


all 7 positions must be present.

Must be in the following format mmmyyyy

The three letter month mmmyyyy must be a valid three letter abbreviation for a month

The three letter month mmmyyyy can be all in upper case or all in lower case

The year mmmyyyy must be numeric and must be at least 18 years less than the current year

Valid three letter abbreviation for the different months are:

all in lower case - jan feb mar apr may jun jul aug sep oct nov dec

all in upper case - JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC

I got the month part to validate, i took the very long route but it works lol. Now for the year part.

this is what I've done



var field4 = document.pizza.field04;
var month = field4.value;
var months = month.substr(0,3); var year = month.substr(3,4);
var toDate = new Date();
var toYear = toDate.getFullYear();


if(isNaN(year))
{
errMessages += "<li class='b1'>d.o.b 4digits at the end</li>\n";
errMessages += "<li class='b2'>ex: xxx1993</li>\n";
}


else if( eval('year - toDate') <18)
{
errMessages += "<li> error you're not 18</li>"
}


return errMessages;



what am i doing wrong? I want to validate the user's input. If the user enters a year that is 18 years less than the current year, to be an error...user must be 18 years old or more to authenticate.

Any help would be greatly appreciated thank you .

Philip M
Apr 8th, 2012, 10:08 AM
if (toYear - year) < 18 {

This is an example of how things get harder if the names of variables are poorly chosen.
It would be much clearer if you did someting like:-


var val = field4.value;
var dobmonth = val.substr(0,3);
var dobyear = Number(val.substr(3,4)) || 0;
var todayDate = new Date(); // i.e. now
var todayYear = todayDate.getFullYear(); // the current year
if (todayYear - dobyear < 18) {

Do not use eval!!!


“There are two kinds of failures: those who thought and never did, and those who did and never thought.” - Dr. Laurence J. Peter quotes (American "hierarchiologist", Educator and Writer, 1919-1990)

ShadowBoss
Apr 8th, 2012, 08:23 PM
Philip, you are awesome man. Thank you, I need to get into the habbit of creating better distinct variables.

Thank you so much man!

Philip M
Apr 9th, 2012, 08:28 AM
I am sure that you realise this, but if you are trying to identify whether someone is under/over 18, it is not sufficient to simply compare the year of birth. You need to consider the month (and day) as well to see if the 18th birthday in this year has been reached.

ShadowBoss
Apr 12th, 2012, 07:52 AM
Yes I did raise that question with my professor but he requested that only the year be checked so I didn't bother. Thanks again!