homepage Welcome to WebmasterWorld Guest from 54.198.148.191
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

This 31 message thread spans 2 pages: 31 ( [1] 2 > >     
JavaScript JumpStart #2 - form validation
part 2
korkus2000




msg:1492346
 12:31 pm on Jun 9, 2003 (gmt 0)

JavaScript JumpStart - Part 2
Form Validation - Part 2

In the last JavaScript JumpStart [webmasterworld.com] we talked about the basics of JavaScript form validation. Now we can look at how to combine these basics to create validation for any form you may have.

Form Object
Before we start lets take a look at the form object. The form object has 2 event handlers; onSubmit and onReset. We covered the onSubmit in the last JumpStart. The onReset is similar, firing off when the form is reset, but you don't need to return a value. onReset is not used much, but can come in handy if you need to process information if the form is reset.

The form object also has methods to fire off these actions; submit() and reset(). Calling these methods will reset the form or submit it.

document.form1.submit(); = submits the form
document.form1.reset(); = resets the form

These can become handy if you want to execute form actions from another page or frame.

Form Elements
First lets look at the different form elements and how they are accessed. You can copy and paste this code into an HTML page, and have it function. Here is a basic form with all the form elements:

<form name="form1">
<input type="text" name="textbox1" value="textbox1" onBlur="alert(document.form1.textbox1.value)"><br>
<input type="hidden" name="hidden1" value="hidden1"><br>
<textarea cols="10" rows="5" name="textarea1" onBlur="alert(document.form1.textarea1.value)">textarea1</textarea><br>
<input type="password" name="password1" value="password1" onBlur="alert(document.form1.password1.value)"><br>
<input type="radio" name="radio1" value="radio11" onclick="alert(document.form1.radio1[ 0 ].checked)">
<input type="radio" name="radio1" value="radio12" onclick="alert(document.form1.radio1[ 1 ].checked)">
<input type="radio" name="radio1" value="radio13" onclick="alert(document.form1.radio1[ 2 ].checked)"><br>
<input type="checkbox" name="checkbox1" value="checkbox1" onClick="alert(document.form1.checkbox1.checked)"><br>
<select name="select1" onchange="alert(document.form1.select1.options[document.form1.select1.selectedIndex].value)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
<input type="button" name="button1" value="button1" onClick="alert(document.form1.button1.value)"><br>
<input type="submit" name="submit1" value="submit1" onClick="alert(document.form1.hidden1.value)"><br>
</form>

I have added alerts to each element using the corresponding event handler for that element.

Textbox
We have talked about the text box in the last JumpStart, but lets look at it again.

<input type="text" name="textbox1" value="textbox1" onBlur="alert(document.form1.textbox1.value)">

I have used the onBlur event handler to fire off the alert. When you click inside of a text box it gives it focus. When you click out of it after giving it focus, you blur the textbox. So when we blur the text box it will fire off the alert. In the alert we have the road map to the text box’s value. So when the text box gets blurred it will alert its value.

Textarea

<textarea cols="10" rows="5" name="textarea1" onBlur="alert(document.form1.textarea1.value)">textarea1</textarea>

We have the same thing for the text area.

Password

<input type="password" name="password1" value="password1" onBlur="alert(document.form1.password1.value)">

Again, the same for the password field.

I will mention that you can get the default value for the text area, password and text box by replacing the value in our example with defaultValue:

document.form1.textarea1.defaultValue

You can also get the name and type of the text area, password and text box like this:

document.form1.textarea1.name = the value in the name attribute
document.form1.textarea1.type = the value in the type attribute

Radio Buttons
Radio buttons are a little different. Radio buttons have a click event. So I used their onClick event handler.

<input type="radio" name="radio1" value="radio11" onclick="alert(document.form1.radio1[ 0 ].checked)">
<input type="radio" name="radio1" value="radio12" onclick="alert(document.form1.radio1[ 1 ].checked)">
<input type="radio" name="radio1" value="radio13" onclick="alert(document.form1.radio1[ 2 ].checked)">

We have two things to check with radio buttons the checked property and value property. We need to find out which radio button is checked then find out that buttons value. To do this we need to write a small function that will check the buttons and see which one has been checked. Then we will get its value. So lets look at a function to handle this:

<script language="JavaScript" type="text/javascript">
function whichButton(){
var clickedButton = "";
for(i=0;i<3;i++){
if(document.form1.radio1[ i ].checked == true){
clickedButton = document.form1.radio1[ i ].value;
}
}
alert(clickedButton);
}
</script>

So lets take this one line at a time. First it is nested in script tags to let the browser know that it is javascript code. Next we declare the function using the “function” keyword and the name of the function. Functions are incased in curly brackets so we open and close with curly brackets.

var clickedButton = "";

Here we are declaring a variable and assigning it the value of nothing. When you want to use a variable you should declare it using the “var” keyword. You do not have to assign it, but I did to show you how you can declare and assign variables on the same line. We close with the JavaScript end of line character the semicolon.

So now we have a variable we can use in the function “clickedButton” with basically no value. JavaScript is case sensitive so if we called clickedbutton later on, JavaScript wouldn’t know what to do with it. It must have the capital B to be the variable we just declared.

for(i=0;i<3;i++){

for loop
In the last JumpStart we talked about the if and if…else statements. Now lets look at loops. The most common is the for loop. Loops iterate through a code block. for loops iterate through a code block a certain number of times. The loop starts out with the for keyword. Then open parenthesis.

i=0;

Here we are assigning the variable i the value of 0 and using a semicolon to tell JavaScript that we are done with this statement. We did not declare i with the var keyword, and don't have to. You could if you wanted like this:

for(var i=0;i<3;i++){

JavaScript starts with the number 0. When you are counting in JavaScript remember to always start at 0 and not 1. Since we had 3 radio buttons we need the loop to go 3 times.

i<3;

So we tell the loop that we want it to process the loop until i equals 3. So it will start at 0 and end at 2. It will not run once i = 3 since we told it to only run if i < 3. Again we tell it that we are done with this command with a semicolon.

i++){

++ is to auto increment i. It is equal to i = i + 1. So every time the loop runs i will have 1 added to it until it reaches 3. Since the ++ is after i, it will increment by one after the loop. If it were before the i it would increment before the loop. There is also -- which is the auto decrement. Then we close the expression with a close parenthesis. And open a bracket to contain the code block we will loop through.

if(document.form1.radio1[ i ].checked == true){
clickedButton = document.form1.radio1[ i ].value;
}

Now we have an if statement that tests each radio button to see if it is checked. JavaScript puts every element on the page in an array. An array is a variable that can hold many values. You specify which value you want by putting the number of the item located in the array. So to access the first radio button or radio11 we call the radio button name radio1 then the number of the position the first button is in the array. Since it is the first radio button we want, we would call radio1[ 0 ]. Why radio1[ 0 ]? Because JavaScript starts at 0 and not 1.

if(document.form1.radio1[ i ].checked == true){

So the first go around the loop radio1[ i ] = radio1[ 0 ] because i=0. After the loop runs once it auto increments i and i becomes 2 making it radio1. Next it increments and i becomes 2. Then as it finishes that it will end because i will not be less than 3.

So we are trying to find which button is checked. A checked button will have a checked property == true. Remember we use == to see if the 2 values are the same and = to assign a new value.

clickedButton = document.form1.radio1[ i ].value;

Once the if statement gets a radio button that == true it will fire off its code block. This code block is assigning the value of the checked radio button to the variable clickedButton. Then we close the if statement with a close curly bracket. Then close the for loop with a close curly bracket.

alert(clickedButton);
}

We then alert the value of the variable to see that it is working. We place the alert outside of the curly brackets for both the loop or we would have three alert boxes to close. Then we close the function. We will not be using the value for what we are doing here, but I thought it would be a good chance to see how you would do it. For this we only want to make sure that a radio button has been clicked.

Checkbox

<input type="checkbox" name="checkbox1" value="checkbox1" onClick="alert(document.form1.checkbox1.checked)">

Checkboxes are like radio buttons since they are either on or off. They are just not tied to other checkboxes. With checkboxes you want to check to see if it is checked. Checkboxes and radio buttons have the checked, defaultChecked, name, type and value properties. Radio buttons also have the length property.

Select Box

<select name="select1" onchange="alert(document.form1.select1.options[document.form1.select1.selectedIndex].value)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

Select boxes are very common elements in forms. Like radio buttons they have multiple options. These options are kept in an array. JavaScript has given us a nifty way of accessing the value that is selected. We use the select’s options array. Inside the array we give the JavaScript a road map to the select we want, and ask for its selectedIndex property.

document.form1.select1.options[document.form1.select1.selectedIndex].value

This line gives us the current value of the select element. We can also get the text property this way.

Buttons and Submit Buttons

<input type="button" name="button1" value="button1" onClick="alert(document.form1.button1.value)">

Buttons and submits are basically the same thing in JavaScript. Submits do submit the form, but all properties of a button will work on a submit. Usually we don’t want to access the elements, but we can if needed. You can find the value, name, and type.

Hidden Fields

<input type="hidden" name="hidden1" value="hidden1">
<input type="submit" name="submit1" value="submit1" onClick="alert(document.form1.hidden1.value)">

Hidden fields are hidden so they are not accessible by their own events. We need to trigger an event to access the hidden element, so I used a submit button. You can access the type, name, and value of a hidden field.

JavaScript Comments
JavaScript also has comment characters. It is //. Anything after a // will not be read or parsed by JavaScript. The problem with that is URLs have http://. These will start a comment. The way around that is to escape these characters. You do this with a \. So to stop a comment with http://www.webmasterworld.com would be to add the \ in between the // like this http:/\/www.webmwsterworld.com. JavaScript will know that \/ is really /.

Validation Function
So lets look at making sure our original form has all of the fields filled out. We will write a function that tests each field and will alert the user of all fields not needed. We will be removing the hidden field and the button since users cannot fill these elements out. So here is our new form with an onsubmit event handler calling our validation function. We have also added a dummy option in the select box with no value. This will let us know if nothing has been selected.

<form action="" name="form1" onsubmit="return checkFields()">
<input type="text" name="textbox1"><br>
<textarea cols="10" rows="5" name="textarea1"></textarea><br>
<input type="password" name="password1"><br>
<input type="radio" name="radio1" value="radio11">
<input type="radio" name="radio1" value="radio12">
<input type="radio" name="radio1" value="radio13"><br>
<input type="checkbox" name="checkbox1" value="checkbox1"><br>
<select name="select1"">
<option value="">Make a Selection</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select><br>
<input type="submit" name="submit1" value="submit1"><br>
</form>

Now we need a checkFields function to validate the form. I will use comments for commentary for the sake of space.

<script language="JavaScript">
function checkFields() {
emptyfields = "";
if (document.form1.textbox1.value == "") {
emptyfields += "\n - Textbox1";
}
if(document.form1.textarea1.value == "") {
emptyfields += "\n - Textarea1";
}
if (document.form1.password1.value == "") {
emptyfields += "\n - Password1";
}
var clickedButton = "";
for(i=0;i<3;i++){
if(document.form1.radio1[ i ].checked == true){
clickedButton = "true";
break
}
}
if (clickedButton == "") {
emptyfields += "\n - Radio1";
}
if (document.form1.checkbox1.checked == false) {
emptyfields += "\n - Checkbox1";
}
if (document.form1.select1.options[document.form1.select1.selectedIndex].value == "") {
emptyfields += "\n - Select1";
}


if (emptyfields!= "") {
emptyfields = "These fields are required:\n" +
emptyfields + "\n\nPlease fill in all required feilds";
alert(emptyfields);
return false;
}
else return true;
}
</script>

So lets take a look at this function.

//First we declare the checkFields function with the function keyword.
function checkFields() {
//We declare an emptyfields variable and set its value to “”.
emptyfields = "";
//We use an if statement to see if the textbox has a value entered or not.
//Without a value attribute text fields have a value of “” in JavaScript.
if (document.form1.textbox1.value == "") {
//We will now assign a sting to our emptyfields variable.
//We use the += operator to add our string to the end of the current value
//and not write over the current value.
//It doesn’t matter the first time but later it will.
//We are using this variable to hold all of the fields not completed
//to alert the user which ones they missed.
//We add a little formatting to the string so it is more useable
//with spaces and a -.
//I will explain the \n later in the function.
emptyfields += "\n - Textbox1";
}

//Basically the same as the textbox
if(document.form1.textarea1.value == "") {
emptyfields += "\n - Textarea1";
}

//Basically the same as the textbox
if (document.form1.password1.value == "") {
emptyfields += "\n - Password1";
}

//With the radio button we need to loop through the buttons
//to see if any have been clicked.
//We declare our variable that will tell us if one has been clicked or not.
var clickedButton = "";
//Start our for loop.
for(i=0;i<3;i++){
//Check to see if the current button has been clicked.
if(document.form1.radio1[ i ].checked == true){
//If the current button in the loop has been clicked
//we set our variable to "true".
//It could be anything really, we just don’t want it equal to "".
clickedButton = "true";
//We use the break keyword to stop the loop since we found a button clicked.
break
}
}

//Now we use the clickedButton variable to test.
if (clickedButton == "") {
emptyfields += "\n - Radio1";
}

//Since this is a checkbox we check to see if the checked property is true or false.
if (document.form1.checkbox1.checked == false) {
emptyfields += "\n - Checkbox1";
}

//Since we created a dummy option with the value of "",
//we look to see if that is still the value.
if (document.form1.select1.options[document.form1.select1.selectedIndex].value == "") {
emptyfields += "\n - Select1";
}

//Now we have check all of our fields
//We need to alert the user, which required fields they missed
//so they can complete the form.
//We check to see if the emptyfields variable has anything in it.
//We use the!= operator or not equal to.
//We are saying if the emptyfields variable is not equal to the original value
//then do this code block.
if (emptyfields!= "") {
//If there is something other than the original value,
//we take our emptyfields variable and create a usable alert for our user.
//We want to combine all of these values into something
//users can use. We use the + operator on strings to concatenate them.
//Concatenation just means to tack strings together to make one big string.
//So we take the first value we want on the alert box.
//We follow this with \n. \n is the new line character in JavaScript.
//It makes the next string start on a new line like <br>
//would in HTML. Then the + to tack on the next string.
emptyfields = "These fields are required:\n" +
//Now we want to add the strings we built in the if statements above.
//Since JavaScript evaluates before assigning we will still have
//those earlier values before overwriting them.
//Then we add more instructions for our users.
//To make the alert box less cluttered I added 2 new line characters
//before the instructions.
emptyfields + "\n\nPlease fill in all required feilds";
//Then we alert the value.
alert(emptyfields);
//Now we tell the form not to submit by returning false.
return false;
}

//If emptyfields was the original value we return true
//to tell the form to continue submitting.
else return true;
}

The Alert
If you don’t fill out any fields the alert box should have this text:

These fields are required:

- Textbox1
- Textarea1
- Password1
- Radio1
- Checkbox1
- Select1

Please fill in all required fields

To me this is much more informative to the user and will help alleviate frustration filling out forms.

So that’s it. I have rambled on enough. Hopefully JavaScript is starting to make more sense.

[1][edited by: korkus2000 at 1:01 pm (utc) on June 9, 2003]

 

tigger




msg:1492347
 12:34 pm on Jun 9, 2003 (gmt 0)

WOW great posting man :)

BlobFisk




msg:1492348
 12:46 pm on Jun 9, 2003 (gmt 0)

Fantastic post korkus - consise, easy to understand and fantastically informative.

edit_g




msg:1492349
 12:52 pm on Jun 9, 2003 (gmt 0)

I just sat a tech test for a new job on form validation! Damnit - you're 2 hours late! ;)

Otherwise I think just WOW sums it up pretty nicely - well done! :)

korkus2000




msg:1492350
 1:24 pm on Jun 9, 2003 (gmt 0)

I also want to point out that array values have spaces in them like:

document.form1.radio1[ 0 ].checked;

They don't have to have spaces and normally they would look like this:

document.form1.radio1[0].checked;

But the forum has style codes for font sizes and it made the post strange. So I added a space before and after the number to make the post not have different font sizes. I believe that spaces will work in all browsers (It does in IE), but if the array sections don't work for you then take out the spaces.

mattglet




msg:1492351
 4:48 pm on Jun 9, 2003 (gmt 0)

korkus,
what do you think the percentage of people is that block javascript in their browsers? i've never liked to use javascript in my sites (especially for form validation) b/c there's always going to be people that block javascript, and the site will throw up nasty errors when they try to submit.

i use server side form validation, and while it creates a lot of work for me, i know that 99.999% of the forms that are passed, work perfectly, and catch all the errors. where as a (unknown) percentage of people might be turned away from my sites because they have javascript blocked, and in turn will get nasty errors.

i'm not disputing the need for javascript, i in fact wish i could use it more. but because i don't want to take a chance with browsers blocking it, the risk outweighs my reward. i am just curious as to what your (and others) ideas are regarding this.

-Matt

korkus2000




msg:1492352
 5:07 pm on Jun 9, 2003 (gmt 0)

I use server-side to check everything. I use javascript to take the load off if JS is turned on. I make sure there is always a server-side back up though. It can save cpu time on the server greatly, eventhough you may have a backup. You will also catch problems immediately for those people who have JavaScript turned on. The large majority have javascript turned on anyway. I do agree that completely relying on JavaScript is not the best option.

Javascript is very benificial even with server-side scripting. When you are getting lots of traffic even a little client-side processing can make a difference.

limbo




msg:1492353
 5:23 pm on Jun 9, 2003 (gmt 0)

Thanks Korkus!

That will take some digesting.

Good job I'm feeling hungry

Ta

Liam

jatar_k




msg:1492354
 5:38 pm on Jun 9, 2003 (gmt 0)

killer thread korkus,

As far as the server/client split there are a lot of advantages to using javascript. Form validation with js is a great load saver for scripts. I try to do most of my form validation with js (still testing baseline values with php). It keeps people on the page and keeps them from having to hit the back button or from the server having to parse the form and reserve it every time they make an error.

In my experience most people surf with javascript on. I even use php to dynamically write the js. On a really busy site you could save yourself tens of thousands of page views, if not more, in some cases.

It comes down to the right tool for the right job. Using the scripts to do everything is ok but relieving the stress by putting as much as possible onto the client is extremely useful. You need to look at each individual case or functin of the site and where there is a case for each you weigh the pros and cons and base your decision on that.

mattglet




msg:1492355
 8:08 pm on Jun 9, 2003 (gmt 0)

korkus-
you said "...if JS is turned on." is there a way to check to see if the client has js enabled?

even if you use server-side checking as a backup, you still have to run the server-side code either way don't you?

i.e. if you use js as a client side check, that's only going to save the user from clicking back, etc. i'm not sure how it saves CPU overall. am i missing something?

-Matt

jatar_k




msg:1492356
 8:13 pm on Jun 9, 2003 (gmt 0)

If you validate the form with js on page then they never request a new page until the data is validated. With server side every time they try to validate the form the script is requested, run then outputs or forwards on success.

korkus2000




msg:1492357
 2:14 am on Jun 10, 2003 (gmt 0)

>>is there a way to check to see if the client has js enabled?

There are components that do this. You can also use js to submit a form or request an item that you can track. If they request the picture or item then they have js enabled.

dmorison




msg:1492358
 3:39 am on Jun 10, 2003 (gmt 0)

Great post, but personally I don't see any point in Javascript form validation.

Especially for very high traffic sites!

Firstly, you have to validate form input server side anyway.

Secondly, people don't purposely go around filling in forms incorrectly; so if they have made a mistake I want to know why, and use the information to improve usability. (I log rejected form submission and study the results)

Thirdly, given that you have improved your usability, and the other reasons for invalid input cannot be helped via JavaScript anyway, then for a high traffic site why waste megabytes of bandwidth everyday with megabytes of JavaScript on every form when it will only occasionally be of any use to someone.

Anyway, I know i'm virtually alone in this opinion, so i'll get me coat!

BlobFisk




msg:1492359
 9:27 am on Jun 10, 2003 (gmt 0)

I think that both client-side and server-side validation have their merits, and a time when they should and should not be used. On large sites, with complex submission forms I feel that server-side validation is the answer. We recently worked on a large eCommerce site with a number of different forms that required validation - for this we have a seperate Java Bean that was responsible for all form validation.

On smaller sites (with more straightforward forms), with less traffic, I feel that client side validation (as korkus has outlined above) is a perfectly valid (excuse the pun) solution.

ShawnR




msg:1492360
 9:43 am on Jun 10, 2003 (gmt 0)

"...if they have made a mistake I want to know why, and use the information to improve usability..."

That is an excellent point. The flip side is that client-side form validation improves usability, as it gives users faster more immidiate feedback. Entry errors are often not related to usability problems; simply typos.

... there probably isn't a 'right' answer, though.

korkus2000




msg:1492361
 12:42 pm on Jun 10, 2003 (gmt 0)

Here is an interview with Danny Goodman [webword.com] about JavaScript and usability.

JavaScript's greatest potential gift to a Web site is that scripts can make the page more immediately interactive, that is, interactive without having to submit every little thing to the server for a server program to re-render the page and send it back to the client.

>>Secondly, people don't purposely go around filling in forms incorrectly; so if they have made a mistake I want to know why, and use the information to improve usability. (I log rejected form submission and study the results)

The most common mistake is accidentally hitting the enter key and submitting the form. This submits incomplete info. I do this all the time and everyone I see fill out forms does this. Thats why trapping required fields on the client site is important.

I am surprized you would track all of your forms inputs. That is a lot of space to keep that information, definitely for high traffic sites. I suggest you take samplings. You reach a point with a form where you cannot enhance it for the majority. You start to recomplicate inputs after a certian point. Samplings are great, but at some point that information becomes useless and not worth the space.

>>Thirdly, given that you have improved your usability, and the other reasons for invalid input cannot be helped via JavaScript anyway

You should never assume you have enhanced your usability so much that you cannot expect mistakes. Unless you set up training for the site, and even then people get it wrong, you just can't stop mistakes. I work on intranet and web apps with usability engineers, and trust me no matter how much you train and people use it, errors will always be present.

Going back and forth to the server for people with dial up modems is frustrating. People abandon forms all the time because they have to wait to make sure they have entered everything right. JavaScript validation for fields that haven't been filled out is a very usefull tool. If you are processing a large amount of server-side processes for a high traffic site then it will save you money on upgrades.

korkus2000




msg:1492362
 1:18 pm on Jun 10, 2003 (gmt 0)

I also want to add that this JavaScript code works in (tested) NN4+, IE4+, and Opera 7. It should work in NN3, IE3, and Opera 6. The Javascript is part of the original spec that dealt with forms and the dom.

celerityfm




msg:1492363
 1:29 pm on Jun 10, 2003 (gmt 0)

Don't think this has been mentioned yet in this thread, but everyone should also take a look at Netscape's (the author of Javascript) form validation sample code site [developer.netscape.com]. The site includes this widely used javascript file, formchek.js [developer.netscape.com] that includes the following functions:

isWhitespace, isLetter, isDigit, isLetterOrDigit, isInteger, isSignedInteger, isPositiveInteger, isNonnegativeInteger, isNegativeInteger, isNonpositiveInteger, isFloat, isSignedFloat, isAlphabetic, isSSN, isUSPhoneNumber, isInternationalPhoneNumber, isZIPCode, isStateCode, isEmail, isYear, isIntegerInRange, isMonth, isDay, daysInFebruary, stripCharsNotInBag , stripWhitespace , stripInitialWhitespace, reformat, reformatZIPCode, reformatSSN, reformatUSPhone , prompt, promptEntry, warnEmpty, warnInvalid, checkString, checkStateCode, checkZIPCode, checkUSPhone, checkInternationalPhone, checkEmail, checkSSN, checkYear, checkMonth, checkDay, checkDate, getRadioButtonValue, checkCreditCard, isCreditCard, isVisa, isMasterCard, isAmericanExpress, isDinersClub, isCarteBlanche, isDiscover, isEnRoute, isJCB, isAnyCard, isCardMatch

The functions operate exactly as they are described pretty much. The formchek.js is a great resource, a must for javascript form validation!

korkus2000




msg:1492364
 1:39 pm on Jun 10, 2003 (gmt 0)

Those are great JavaScripts celerityfm. One of the points of this thread though, is for people to understand how they work. The problem with always using these types of copy paste scripts is you are in trouble if you need to modify them. A basic understanding of JavaScript should be as important as knowledge of HTML.

celerityfm




msg:1492365
 1:53 pm on Jun 10, 2003 (gmt 0)

Korkus2000 - I highly agree with you, and I must say these Jumpstart threads are highly informative! This was a case of not reading carefully enough and posting, doh.

In any case, the neat part about the formchek.js script is that you *can* modify it, and Netscape even has a nice testing page that you can use to double check your modifications, available at the site I linked in my previous post. Plus formchek.js is almost a primer in itself if you read through the source there are lots of good comments that helped me out when I was just starting.

But nothing feels as good as writing your code clean, from scratch! Keep up the good work!

dmorison




msg:1492366
 1:53 pm on Jun 10, 2003 (gmt 0)

You're advocating using JavaScript even after refining your form by studying feedback.

This is what I don't understand.

Once you have used feedback to reduce the first time input error rate to an absolute minimum then why waste bandwidth on tons of JavaScript just for odd occasion on which it might help.

Going back and forth to the server for people with dial up modems is frustrating.

They shouldn't have to be. You've already refined your forms to reduce input error rate to the absolute minimum.

How about saving your modem users the bother of downloading superfluous JavaScript instead?

ShawnR




msg:1492367
 2:19 pm on Jun 10, 2003 (gmt 0)

Great discussion... but I'm a bit concerned it might subvert the original intent of the post, which was to provide a Javascript jumpstart. There are always arguments for and against, and Javascript is a hot button for many. Those who favour pure server-side solutions can probably find arguments to show that almost anything commonly done with Javascript can be done without it. e.g. reframing: the answer would be don't use frames; mouseover: the answer would be use css; cookies: the answer would be use a server-side scripting language; etc.. All good arguments, depending on the context, but in most cases there is also a valid counter-argument. I'd hate to see us go through these pro vs anti javascript arguments every time Korkus posts another installment to his great tutorial. Javascript is an important part of the web.

Let me know if I'm alone in thinking this way, in which case I'll happily apologise and pull my head in.

korkus2000




msg:1492368
 3:37 pm on Jun 10, 2003 (gmt 0)

Pro/Con JavaScript discussion has moved to this thread:
[webmasterworld.com...]

photon




msg:1492369
 5:36 pm on Jun 19, 2003 (gmt 0)

Korkus--

It looks that you're checking each required field explicitly for blanks. If you add another required field, you then have to add another if statement to handle that instance.

I've had success with adding an attribute to the input tag:
<input type="text" name="creditcard" id="credit card number" [b]required="true"[/b]>

Then my validation javascript as one of its checks loops through the form elements thusly:
if (form_items[i].required == "true" && value.length == 0)
{
err_msg = err_msg + ''\n-- '' + id + '' is a required field'';
className = "badInput";
no_errors = false;
}

That way even if I add additional required fields--or want to change a field from not required to required or vice versa--I just make the change in the HTML. The javascript doesn't need to be changed. One caveat: you then have to use the required attribute on all form elements, or you'll get a javascript error.

The only issue I have with it is that my code does not validate as XHTML Strict because of the required attribute. Anyone know of a way around that?

<edit>elucidation, and correction of bad coding</edit>

korkus2000




msg:1492370
 5:51 pm on Jun 19, 2003 (gmt 0)

photon do you know what the browser compatibility of the required attribute of a form element is?

photon




msg:1492371
 6:05 pm on Jun 19, 2003 (gmt 0)

It's actually an attribute I just made up (that's why it won't validate). It's not part of the HTML standard, but for some reason javascript has no trouble accepting it.

I've only tested it with IE6, which seems to have no problem with it.

<edit>More elucidation</edit>

ShawnR




msg:1492372
 10:22 pm on Jun 19, 2003 (gmt 0)

"... use the required attribute on all form elements... The only issue I have with it is that my code does not validate as XHTML Strict because of the required attribute. Anyone know of a way around that? ..."

The way I do it is to have the form element name

e.g.
Not required:
<input type="text" name="textbox1" ...

Required:
<input type="password" name="
required_password1" ...

Then I loop through all of the form's elements, testing for whether the name starts with "required", and if so I use a switch to handle the different types of form elememnts.

photon




msg:1492373
 11:48 am on Jun 20, 2003 (gmt 0)

Nice, ShawnR! While I kind of like the straightforwardness of my approach, yours has all of its advantages and will validate also.

I'll start using that in the future.

korkus2000




msg:1492374
 11:55 am on Jun 20, 2003 (gmt 0)

ShawnR, can you share the function where you handle the required string and test for it? I think it is a great idea.

ShawnR




msg:1492375
 12:32 pm on Jun 20, 2003 (gmt 0)

Here it is, warts and all. Feel free to suggest improvements (I have a thick skin...)


//==========================================================
// Configuration variables

var required_prefix = "required_";

//==========================================================
// Functions available externally

function checkRequiredAndSubmit(my_form) {
__if (checkrequired(my_form))
____my_form.submit();
}

function checkRequired_checkEmail_AndSubmit(my_form) {
__if (checkrequired(my_form))
____if (IsEmailValid(my_form, 'required_email'))
______my_form.submit();
}

function IsEmailValid(my_form, elem_name)
{
__// Should do this in a regex instead... This could be tightened up a whole lot...
__var form_elem = my_form.elements[elem_name];
__var AtSym = form_elem.value.indexOf('@');
__var Period = form_elem.value.lastIndexOf('.');
__var Space = form_elem.value.indexOf(' ');
__var Length = form_elem.value.length - 1; // Array is from 0 to length-1

__if ((AtSym < 1) ¦¦ ___________// '@' cannot be in first position
______(Period <= AtSym+1) ¦¦ __// Must be atleast one valid char btween '@' and '.'
______(Period == Length ) ¦¦ ___// Must be atleast one valid char after '.'
______(Space!= -1)) ___________// No empty spaces permitted
__{
____alert('Please enter a valid e-mail address');
____selectText(form_elem);
____return false;
__} else
____return true;
}

function checkrequired(my_form){
__var pass = true;
__var unfilled_fields = "";
__var first_incorrect_field;

__for (i = 0; i < my_form.length; i++) {
____var form_elem = my_form.elements[i];
____if (form_elem.name.substring(0, required_prefix_length) == required_prefix) {
______if (((form_elem.type == "text" ¦¦ form_elem.type == "textarea"
_______________¦¦ form_elem.type == "file" ¦¦ form_elem.type == "password")
________ && form_elem.value == '')
________ ¦¦ (form_elem.type.toString().charAt(0) == "s"
________ && form_elem.selectedIndex == 0))
______{
________unfilled_fields += '\n' + form_elem.name.substring(required_prefix_length, 35);
________if (pass) {
__________first_incorrect_field = form_elem;
__________pass = false;
________}
______}
____}
__}
__if (!pass) {
____alert("Please make sure the following fields are properly completed:\n\n"+unfilled_fields);
____selectText(first_incorrect_field);
__}
__return pass;
}

function selectText(form_elem){
__form_elem.focus();
__form_elem.select();
}

//==========================================================
// Internal Variables and fuctions

var required_prefix_length = required_prefix.length;

(Of course, change the underscores to spaces. They are just there for formatting)

Shawn

This 31 message thread spans 2 pages: 31 ( [1] 2 > >
Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved