/    Sign up×
Community /Pin to ProfileBookmark

Form Validation…Need Help…

Hello.

Sorry folks. This is a rather long one. I would be very greatful for [B]any[/B] suggestions for this. The form validation is supposed to do the following:

Here’s the code:

[B]The form:[/B]

[CODE]
<html><head><title>MyForm</title>
<script type=”text/javascript” src=”Problem16.js”></script>
<style type=”text/css”>

.formstyle {position: absolute;
left: 260px;
top: 75px;
background-color: darkblue;
padding-top:150px;
padding-bottom:50px;
}

.textstyle {
font-family: Arial;
font-size: 11px;
color: white;
}

#messagestyle {position:absolute;
left: 75px;
top: 15px;
border: solid 2px black;
color: lightblue;
}

</style>
</head>
<body bgColor=”black” onLoad=”attachHandlers();”>
<div class=”formstyle”>
<div id=”message”></div>
<table>
<form action=”mailto:[email protected]” method=”post”>
<tr>
<td>
<label for=”Name” class=”textstyle”>Your Name:
<input type=”text” name=”Name” id=”the_name” size=”20″>
</label>
</td>
</tr>
<tr>
<td>
<label for=”Email” class=”textstyle”>E-mail Address:
<input type=”text” name=”Email” id=”the_email” size=”20″>
</label>
</td>
</tr>
<tr>
<td>
<span class=”textstyle”>Please select a city:</span>
<select name=”city” id=”myselections”>
<option selected=”selected”>(none)</option>
<option value=”Chicago”>Chicago</option>
<option value=”Atlanta”>Atlanta</option>
<option value=”D.C.”>Wash D.C.</option>
<option value=”New York”>Chicago</option>
</select>
</td>
</tr>
<tr>
<td>
<label for=”beauty” class=”textstyle” id=”target1″>Who Do You Like More:
<input type=”radio” name=”beauty” value=”Halle” size=”2″ id=”radiochoice”>Halle Berry
<input type=”radio” name=”beauty” value=”Beyonce Knowles” size=”2″>Beyonce Knowles
<input type=”radio” name=”beauty” value=”Rosario Dawson” size=”2″>Rosario Dawson
<input type=”radio” name=”beauty” value=”Jessica Alba” size=”2″ id=”breakpoint”>Jessica Alba
</label>
</td>
</tr>
<tr>
<td>
<label for=”dish” class=”textstyle”>What’s Your Favorite Dish:<br>
<input type=”checkbox” name=”dish” value=”fish” size=”2″>Fish<br>
<input type=”checkbox” name=”dish” value=”chicken” size=”2″ id=”checkchoice”>Chicken<br>
<input type=”checkbox” name=”dish” value=”sphagetti” size=”2″ id=”mainchkbox”>Sphagetti<br>
<input type=”checkbox” name=”dish” value=”rice” size=”2″>Rice
</label>
</td>
<tr>
<tr>
<td>
<input type=”submit” value=”send form” id=”my_button”>
</td>
</tr>
</form>
</table>
</div>
</body>
</html>
[/CODE]

[B]The Script:[/B]

[CODE]
<script type=”text/javascript”>

var error = new createerror();

var errors = new Array();
errors[0]=”Namefield has either blank spaces or been left blank. Please fill in.”;
errors[1]=”Emailfield has either blank spaces or been left blank. Please fill in.”;
errors[2]=”Field has illegal characters. Please fill in letters only.”;
errors[3]=”Not a valid email address.”;
errors[4]=”Please select an city.”;
errors[5]=”Please select at least one favorite dish.”;

function createerror(){

this.val=0;
return this;
}

function attachHandlers(){
var the_button = document.getElementById(“my_button”);
the_button.onclick=checkFormFields;

var radio_sel = document.getElementById(“radiochoice”);
radio_sel.onclick=addRadioOpts;

var chkbox_sel = document.getElementById(“checkchoice”);
chkbox_sel.onclick=addCheckOpts;

}

function addRadioOpts(){

var newrow = document.createElement(“tr”);
var newcell1 = document.createElement(“td”);
var newcell2 = document.createElement(“td”);

var newInput1 = document.createElement(“input”);
newInput1.setAttribute(“type”, “radio”);
newInput1.setAttribute(“name”, “movie”);
newInput1.setAttribute(“size”, “2”);
newInput1.setAttribute(“class”, “textstyle”);
var nameText1 = document.createTextNode(“Swordfish”);

var newInput2 = document.createElement(“input”);
newInput2.setAttribute(“type”, “radio”);
newInput2.setAttribute(“name”, “movie”);
newInput2.setAttribute(“size”, “2”);
newInput2.setAttribute(“class”, “textstyle”);
var nameText2 = document.createTextNode(“Perfect Stranger”);

newInput1.appendChild(nameText1);
newInput2.appendChild(nameText2);
newInput1.appendChild(newInput2);

newcell2.appendChild(newInput1);

newcell1.appendChild(newcell2);
newrow.appendChild(newcell1);

var the_table = document.getElementsByTagName(“table”)[0];
var the_label = document.getElementById(“target1”);
var my_row = the_label.parentNode.parentNode;

the_table.insertBefore(newrow, my_row);

var radio_opts = document.getElementsByTagName(“input”);

for (var i=0; i < radio_opts.length; i++)
{
if (radio_opts[i].nodeName.toLowerCase()==”input”)
{
if (radio_opts[i].name=”beauty”)
{
radio_opts[i].onChange=function(){the_table.removeChild(newrow);}
}
}
}

}

function addCheckOpts(){

var newInput3 = document.createElement(“input”);
newInput3.setAttribute(“type”, “radio”);
newInput3.setAttribute(“name”, “choice”);
newInput3.setAttribute(“size”, “2”);
newInput3.setAttribute(“class”, “textstyle”);
var nameText3 = document.createTextNode(“chicken’n’pasta”);

var newInput4 = document.createElement(“input”);
newInput4.setAttribute(“type”, “radio”);
newInput4.setAttribute(“name”, “choice”);
newInput4.setAttribute(“size”, “2”);
newInput4.setAttribute(“class”, “textstyle”);
var nameText4 = document.createTextNode(“chicken’n’potatoes”);

newInput3.appendChild(nameText3);
newInput4.appendChild(nameText4);
newInput3.appendChild(newInput4);

var my_table = document.getElementsByTagName(“table”)[0];
var the_box = document.getElementById(“mainchkbox”);

my_table.insertBefore(newInput3, the_box);

var chicken_sel = document.getElementById(“checkchoice”);

chicken_sel.onchange=function(){my_table.removeChild(newInput3);}

}

function checkFormFields()
{

var first_field = document.getElementById(“the_name”);
var sec_field = document.getElementById(“the_email”);
var the_sel = document.getElementById(“myselections”);
var sel_opt = the_sel.options[selectedIndex];
var my_inputs = document.getElementsByTagName(“input”);

for (var i=0; i < my_inputs.length; i++)
{
if (my_inputs[i].nodeName.toLowerCase==”input”)
{
if (my_inputs[i].name==”beauty”)
{
var radio_boxes = my_inputs[i];
}

if (my_inputs[i].name==”dish”)
{
var chk_boxes = my_inputs[i];
}
}
}

var correct;
var error_mes=””;

correct=checkBlank(first_field.value, error);

if (!correct)
{
error_mes += errors[error.val] n;
first_field.focus();
return false;
}

correct=checkEmailBlank(sec_field.value, error);

if (!correct)
{
error_mes += errors[error.val] n;
sec_field.focus();
return false;
}

correct=checkValidEmail(sec_field.value, error);

if (!correct)
{
error_mes += errors[error.val] n;
sec_field.focus();
return false;
}

correct=checkIllegalChars(first_field.value, error);

if (!correct)
{
error_mes += errors[error.val] n;
first_field.focus();
return false;
}

correct=checkSelOpts(sel_opts, error);

if (!correct)
{
error_mes += errors[error.val] n;
sel_opts.focus();
return false;
}

correct=checkCheckedOpts(chk_boxes, error);

if (!correct)
{
error_mes += errors[error.val] n;
first_field.focus();
return false;
}

displayErrors(error_mes);
return true;

}

function checkBlank(the_name, error){

if (the_name.length==0)
{
error.val=0;
return false;
}

for(var i=0; i < the_name.length; i++){

if (the_name.charAt(i)!=”” && the_name.charAt(i)!=”t”){
return true;
}
}

error.val=0;
return false;
}

function checkEmailBlank(the_email, error){

if (the_email.length==0)
{
error.val=1;
return false;
}

for(var i=0; i < the_email.length; i++){

if (the_email.charAt(i)!=”” && the_email.charAt(i)!=”t”){
return true;
}
}

error.val=1;
return false;
}

function checkValidEmail(user_email, error){

var my_regexp = /^[w.-]+@([w-]+.)+[a-zA-Z]+$/;

if (!my_regexp.test(the_email))
{
error.val=3;
return false;
}

return true;
}

function checkIllegalChars(theuser_name, error){

var name_exp = /[a-zA-Z]+/;

for(var i=0; i < theuser_name.length; i++)
{
var the_char = theuser_name.charAt(i);

if (!name_exp.text(the_char))
{
error.val=2;
return false;
}

return true;
}

function checkSelOpts(city_opts, error){

if (city_opts!= -1 && city_opts.value !=”none”)
{
return true;
}

error.val=4;
return false;
}

function checkCheckedOpts(check_boxes, error){

for(var i=0; i < check_boxes.length; i++)
{
var ones_chkd = check_boxes[i].checked;

if(!ones_chkd)
{
error.val=5;
return false;
}
}

return true;
}

function displayErrors(the_errors){

var the_field=document.getElementById(“message”);
var the_fieldId = the_field.getAttribute(“id”);

the_field.replace(the_fieldId, “messagestyle”);

the_field.appendChild(the_errors);
}

</script>
[/CODE]

Once again, any help or advice is appreciated. I’m new to JavaScript and this is my longest script thus far.

to post a comment
JavaScript

20 Comments(s)

Copy linkTweet thisAlerts:
@banksworld1986authorSep 15.2008 — This form is suppose to do the following:

  • * That each field has been filled in

  • * The text fields do not contain illegal characters (hyphens, dots, spaces, slashes, and symbols).

  • * The email address has the appropriate positioning for the "@" and the "."

  • * Make sure something is selected for the checkbox options (I'll worry about radio options later).

  • * Choose one radio option and one check box option that has a dependent and display it if

    the parent is selected.
  • Copy linkTweet thisAlerts:
    @FangSep 15.2008 — Why is the external script wrapped in script tags?

    Missing bracket in function checkIllegalChars

    Remove the 'n' in function checkFormFields or concatenate as a string.

    Error in function checkFormFields:var sel_opt = the_sel.options[[COLOR="Blue"]the_sel.[/COLOR]selectedIndex];
    Error in function checkFormFields (not need to check this anyway):if (my_inputs[i].nodeName.toLowerCase[COLOR="Blue"]()[/COLOR]=="input")
    Error message [I]error_mes[/I] is never shown.

    Form tags must be outside table tags.
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 16.2008 — Why is the external script wrapped in script tags?

    Missing bracket in function checkIllegalChars

    Remove the 'n' in function checkFormFields or concatenate as a string.

    Error in function checkFormFields:var sel_opt = the_sel.options[[COLOR="Blue"]the_sel.[/COLOR]selectedIndex];
    Error in function checkFormFields (not need to check this anyway):if (my_inputs[i].nodeName.toLowerCase[COLOR="Blue"]()[/COLOR]=="input")
    Error message [I]error_mes[/I] is never shown.

    Form tags must be outside table tags.[/QUOTE]


    Made all updates. Still nothing.

    The external script is in script tags because that's how it's supposed to be referenced...right?

    http://www.tizag.com/javascriptT/javascriptexternal.php

    Trying to look at it piece by piece. Assuming that everything else is correct, would this piece of code be correct:


    [CODE]
    function displayErrors(the_errors){

    var the_field=document.getElementById("message");
    var the_fieldId = the_field.getAttribute("id");

    the_field.replace(the_fieldId, "messagestyle");

    the_field.appendChild(the_errors);
    }
    [/CODE]


    The errors are supposed to appear in a bordered box at the top of the form. At least that's what I'm attempting.
    Copy linkTweet thisAlerts:
    @FangSep 16.2008 — Problem16.js must not contain script tags.

    Where is function displayErrors fired?
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 16.2008 — Problem16.js must not contain script tags.

    Where is function displayErrors fired?[/QUOTE]


    displayErrors is called at the end of:

    function checkFormFields()

    {...

    return true;

    displayErrors (error_mes);

    }

    If not wrapped in script tags, can it be called like this?

    <link rel="scriptref" type="text/javascript" href="Problem16.js">
    Copy linkTweet thisAlerts:
    @FangSep 16.2008 — &lt;script type="text/javascript" src="Problem16.js"&gt;&lt;/script&gt;

    [B]Problem16.js[/B] must not contain script tags.

    What is the new script and html?
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 16.2008 — Problem16.js must not contain script tags.

    What is the new script and html?[/QUOTE]


    I get what you're saying. Disregard the <link> tag. I was just trying out something.

    So you're saying that I have to place the JavaScript in the <head> tag of the html form itself..right?
    Copy linkTweet thisAlerts:
    @FangSep 16.2008 — Your external file contains script tags, remove them[COLOR="Red"]&lt;script type="text/javascript"&gt;[/COLOR]
    var error = new createerror();
    var errors = new Array();
    .
    .
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 16.2008 — Ohhhhh....sorry...I forgot about that!!

    Deleted the tags and still nothing.
    Copy linkTweet thisAlerts:
    @FangSep 16.2008 — &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
    &lt;html lang="en"&gt;
    &lt;head&gt;
    &lt;title&gt;validation&lt;/title&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;

    &lt;script type="text/javascript"&gt;

    var error = new createerror();

    var errors = new Array();
    errors[0]="Namefield has either blank spaces or been left blank. Please fill in.";
    errors[1]="Emailfield has either blank spaces or been left blank. Please fill in.";
    errors[2]="Field has illegal characters. Please fill in letters only.";
    errors[3]="Not a valid email address.";
    errors[4]="Please select an city.";
    errors[5]="Please select at least one favorite dish.";

    function createerror(){

    this.val=0;
    return this;
    }

    function attachHandlers(){
    var the_button = document.getElementById("my_button");
    the_button.onclick=function(){return checkFormFields();};

    var radio_sel = document.getElementById("radiochoice");
    radio_sel.onclick=addRadioOpts;

    var chkbox_sel = document.getElementById("checkchoice");
    chkbox_sel.onclick=addCheckOpts;

    }

    function addRadioOpts(){

    var newrow = document.createElement("tr");
    var newcell1 = document.createElement("td");
    var newcell2 = document.createElement("td");

    var newInput1 = document.createElement("input");
    newInput1.setAttribute("type", "radio");
    newInput1.setAttribute("name", "movie");
    newInput1.setAttribute("size", "2");
    newInput1.setAttribute("class", "textstyle");
    var nameText1 = document.createTextNode("Swordfish");

    var newInput2 = document.createElement("input");
    newInput2.setAttribute("type", "radio");
    newInput2.setAttribute("name", "movie");
    newInput2.setAttribute("size", "2");
    newInput2.setAttribute("class", "textstyle");
    var nameText2 = document.createTextNode("Perfect Stranger");

    newInput1.appendChild(nameText1);
    newInput2.appendChild(nameText2);
    newInput1.appendChild(newInput2);

    newcell2.appendChild(newInput1);


    newcell1.appendChild(newcell2);
    newrow.appendChild(newcell1);

    var the_table = document.getElementsByTagName("table")[0];
    var the_label = document.getElementById("target1");
    var my_row = the_label.parentNode.parentNode;


    the_table.insertBefore(newrow, my_row);

    var radio_opts = document.getElementsByTagName("input");

    for (var i=0; i &lt; radio_opts.length; i++)
    {
    if (radio_opts[i].nodeName.toLowerCase()=="input")
    { <br/>
    if (radio_opts[i].name="beauty")
    {
    radio_opts[i].onChange=function(){the_table.removeChild(newrow);}
    }
    }
    }

    }

    function addCheckOpts(){


    var newInput3 = document.createElement("input");
    newInput3.setAttribute("type", "radio");
    newInput3.setAttribute("name", "choice");
    newInput3.setAttribute("size", "2");
    newInput3.setAttribute("class", "textstyle");
    var nameText3 = document.createTextNode("chicken'n'pasta");

    var newInput4 = document.createElement("input");
    newInput4.setAttribute("type", "radio");
    newInput4.setAttribute("name", "choice");
    newInput4.setAttribute("size", "2");
    newInput4.setAttribute("class", "textstyle");
    var nameText4 = document.createTextNode("chicken'n'potatoes");

    newInput3.appendChild(nameText3);
    newInput4.appendChild(nameText4);
    newInput3.appendChild(newInput4);


    var my_table = document.getElementsByTagName("table")[0];
    var the_box = document.getElementById("mainchkbox");

    my_table.insertBefore(newInput3, the_box);

    var chicken_sel = document.getElementById("checkchoice");

    chicken_sel.onchange=function(){my_table.removeChild(newInput3);}

    }


    function checkFormFields()
    {

    var first_field = document.getElementById("the_name");
    var sec_field = document.getElementById("the_email");
    var the_sel = document.getElementById("myselections");
    var sel_opt = the_sel.options[the_sel.selectedIndex];
    var my_inputs = document.getElementsByTagName("input");

    for (var i=0; i &lt; my_inputs.length; i++)
    {
    if (my_inputs[i].nodeName.toLowerCase()=="input")
    {
    if (my_inputs[i].name=="beauty")
    {
    var radio_boxes = my_inputs[i];
    }

    <i> </i> if (my_inputs[i].name=="dish")
    <i> </i> {
    <i> </i>var chk_boxes = my_inputs[i];
    <i> </i> }
    <i> </i>}
    }

    var correct;
    var error_mes="";

    correct=checkBlank(first_field.value, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    first_field.focus();
    //return false;
    }

    correct=checkEmailBlank(sec_field.value, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    sec_field.focus();
    //return false;
    }

    correct=checkValidEmail(sec_field.value, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    sec_field.focus();
    //return false;
    }

    correct=checkIllegalChars(first_field.value, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    first_field.focus();
    //return false;
    }

    correct=checkSelOpts(sel_opt, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    sel_opt.focus();
    //return false;
    }

    correct=checkCheckedOpts(chk_boxes, error);

    if (!correct)
    {
    error_mes += errors[error.val] + '&lt;br&gt;';
    first_field.focus();
    //return false;
    }

    if(error_mes!="") {
    displayErrors(error_mes);
    return false;
    }
    return true;

    }

    function checkBlank(the_name, error){

    if (the_name.length==0)
    {
    error.val=0;
    return false;
    }

    for(var i=0; i &lt; the_name.length; i++){

    if (the_name.charAt(i)!="" &amp;&amp; the_name.charAt(i)!="t"){
    return true;
    }
    }

    error.val=0;
    return false;
    }


    function checkEmailBlank(the_email, error){

    if (the_email.length==0)
    {
    error.val=1;
    return false;
    }

    for(var i=0; i &lt; the_email.length; i++){

    if (the_email.charAt(i)!="" &amp;&amp; the_email.charAt(i)!="t"){
    return true;
    }
    }

    error.val=1;
    return false;
    }


    function checkValidEmail(user_email, error){

    var my_regexp = /^[w.-]+@([w-]+.)+[a-zA-Z]+$/;

    if (!my_regexp.test(user_email))
    {
    error.val=3;
    return false;
    }

    return true;
    }


    function checkIllegalChars(theuser_name, error){

    var name_exp = /[a-zA-Z]+/;

    for(var i=0; i &lt; theuser_name.length; i++)
    {
    var the_char = theuser_name.charAt(i);

    <i> </i>if (!name_exp.text(the_char))
    <i> </i>{
    <i> </i> error.val=2;
    <i> </i> return false;
    <i> </i>}
    <i> </i>}

    <i> </i>return true;
    }

    function checkSelOpts(city_opts, error){

    if (city_opts!= -1 &amp;&amp; city_opts.value !="none")
    {
    return true;
    }

    error.val=4;
    return false;
    }

    function checkCheckedOpts(check_boxes, error){

    for(var i=0; i &lt; check_boxes.length; i++)
    {
    var ones_chkd = check_boxes[i].checked;

    if(!ones_chkd)
    {
    error.val=5;
    return false;
    }
    }

    return true;
    }

    function displayErrors(the_errors){
    var the_field=document.getElementById("message");
    the_field.innerHTML=the_errors;
    }

    &lt;/script&gt;
    &lt;style type="text/css"&gt;
    .formstyle {position: absolute;
    left: 260px;
    top: 75px;
    background-color: darkblue;
    padding-top:150px;
    padding-bottom:50px;
    }

    .textstyle {
    font-family: Arial;
    font-size: 11px;
    color: white;
    }

    #messagestyle {position:absolute;
    left: 75px;
    top: 15px;
    border: solid 2px black;
    color: lightblue;
    }


    &lt;/style&gt;
    &lt;/head&gt;
    &lt;body bgColor="black" onLoad="attachHandlers();"&gt;
    &lt;div class="formstyle"&gt;
    &lt;div id="message"&gt;&lt;/div&gt;
    &lt;table&gt;
    &lt;form action="mailto:[email protected]" method="post"&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="Name" class="textstyle"&gt;Your Name:
    &lt;input type="text" name="Name" id="the_name" size="20"&gt;
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="Email" class="textstyle"&gt;E-mail Address:
    &lt;input type="text" name="Email" id="the_email" size="20"&gt;
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;span class="textstyle"&gt;Please select a city:&lt;/span&gt;
    &lt;select name="city" id="myselections"&gt;
    &lt;option selected="selected"&gt;(none)&lt;/option&gt;
    &lt;option value="Chicago"&gt;Chicago&lt;/option&gt;
    &lt;option value="Atlanta"&gt;Atlanta&lt;/option&gt;
    &lt;option value="D.C."&gt;Wash D.C.&lt;/option&gt;
    &lt;option value="New York"&gt;Chicago&lt;/option&gt;
    &lt;/select&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="beauty" class="textstyle" id="target1"&gt;Who Do You Like More:
    &lt;input type="radio" name="beauty" value="Halle" size="2" id="radiochoice"&gt;Halle Berry
    &lt;input type="radio" name="beauty" value="Beyonce Knowles" size="2"&gt;Beyonce Knowles
    &lt;input type="radio" name="beauty" value="Rosario Dawson" size="2"&gt;Rosario Dawson
    &lt;input type="radio" name="beauty" value="Jessica Alba" size="2" id="breakpoint"&gt;Jessica Alba
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="dish" class="textstyle"&gt;What's Your Favorite Dish:&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="fish" size="2"&gt;Fish&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="chicken" size="2" id="checkchoice"&gt;Chicken&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="sphagetti" size="2" id="mainchkbox"&gt;Sphagetti&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="rice" size="2"&gt;Rice
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;input type="submit" value="send form" id="my_button"&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;/form&gt;
    &lt;/table&gt;
    &lt;/div&gt;

    &lt;/body&gt;
    &lt;/html&gt;
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 16.2008 — Okay...

    I'll try this out once I get back from work tonight. Thanks.
    Copy linkTweet thisAlerts:
    @konithomimoSep 16.2008 — Why are you appending input objects to input objects and cells to cells? The input objects should be appended to the cells, and the cells should be appended to the row:

    newInput1.appendChild(newInput2);

    newcell2.appendChild(newInput1);


    newcell1.appendChild(newcell2);
    newrow.appendChild(newcell1);


    should be:

    newcell2.appendChild(newInput1);
    newcell2.appendChild(newInput2);
    newrow.appendChild(newcell1);//This is an empty cell . . . perhaps it is not needed
    newrow.appendChild(newcell2);//This contains the 2 input objects
    Copy linkTweet thisAlerts:
    @konithomimoSep 16.2008 — Also, why are you appending textnodes to the radio inputs? Radio inputs do not have any display text. The textnodes need to be appended to the cells. Most likely you need to make this:


    newInput1.appendChild(nameText1);
    newInput2.appendChild(nameText2);
    newInput1.appendChild(newInput2);

    newcell2.appendChild(newInput1);


    newcell1.appendChild(newcell2);
    newrow.appendChild(newcell1);


    this:

    newcell1.appendChild(newInput1);
    newcell1.appendChild(nameText1);
    newcell2.appendChild(newInput2);
    newcell2.appendChild(nameText2);

    newrow.appendChild(newcell1);
    newrow.appendChild(newcell2);


    This will produce:

    &lt;tr&gt;&lt;td&gt;&lt;input type="radio" ...&gt;Swordfish&lt;/td&gt;&lt;td&gt;&lt;input type="radio" ...&gt;Perfect Stranger&lt;/td&gt;&lt;/tr&gt;
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 17.2008 — <i>
    </i>...

    function attachHandlers(){
    var the_button = document.getElementById("my_button");
    [COLOR="Blue"]the_button.onclick=function(){return checkFormFields();};[/COLOR]
    ...
    }
    [/QUOTE]


    Okay, I understand this. The function returns false if error_mes is filled with anything...returns true if not. So you added an anonymous function. Cool.

    <i>
    </i>...
    function addRadioOpts(){

    newInput1.appendChild(nameText1);
    newInput2.appendChild(nameText2);
    newInput1.appendChild(newInput2);

    newcell2.appendChild(newInput1);


    newcell1.appendChild(newcell2);
    newrow.appendChild(newcell1);

    ...
    [/QUOTE]


    This was changed to the recommendations by konlithimimo below.

    <i>
    </i>...
    function displayErrors(the_errors){
    var the_field=document.getElementById("message");
    the_field.innerHTML=the_errors;
    }
    ...
    [/QUOTE]


    After copying and pasting your code, then running it, only 3 errors are displayed when nothing is filled out. The radio options and checkbox options are ignored. The additional radio options or checkbox options don't appear, and once you enter your name or email into the text box without filling out anything else, the form goes through.

    I'll continue to play with it to find a solution. Any more suggestions?
    Copy linkTweet thisAlerts:
    @FangSep 17.2008 — I'll continue to play with it to find a solution. Any more suggestions?[/QUOTE]
    Read how to do basic validation: http://www.yourhtmlsource.com/javascript/formvalidation.html
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 17.2008 — Read how to do basic validation: http://www.yourhtmlsource.com/javascript/formvalidation.html[/QUOTE]

    Will do so...thanks for the link.
    Copy linkTweet thisAlerts:
    @konithomimoSep 17.2008 — 
  • 1. If you are going to assign an onclick for a button then use a normal button and not a submit button.

  • 2. If you use a submit button then use the onsubmit of the form and not the onclick of the button.


  • by using the onclick of the button you are not preventing the submit action from completing, thus the form will submit when you don't want it to.

  • 3. setAttribute('name' does not work in IE. You should use the try and catch method:


  • try{
    var newInput1 = document.createElement('&lt;input type="radio" name="movie" size=2 class="textstyle" value="swordfish"&gt;')
    }catch(E){
    var newInput1 = document.createElement('input');
    newInput1.type = "radio";
    newInput1.name = "movie";
    newInput1.size = 2;
    newInput1.className = 'textstyle';
    newInput1.value = 'swordfish';
    }


  • 4. You need to change the following lines:


  • newInput3.appendChild(nameText3);
    newInput4.appendChild(nameText4);
    newInput3.appendChild(newInput4);


    Check boxes do not have display text. the problem is the same as my last post about the radio buttons.

  • 5. As I said in another of your threads, this line:


  • if (my_inputs[i].nodeName.toLowerCase()=="input")

    Should be :

    if (my_inputs[i].type.toLowerCase()=="radio")

    if you want to check the radio boxes, but since you are trying to check both radios and checkboxes, it is not needed

  • 6. These lines:


  • if (my_inputs[i].name=="beauty")
    {
    var radio_boxes = my_inputs[i];
    }

    if (my_inputs[i].name=="dish")
    {
    var chk_boxes = my_inputs[i];
    }

    are

    a) written wrong, because it will leave you with only the last of each object

    b) not needed.

    You need to use arrays. the easiest way is:

    var radio_boxes = document.getElementsByName('beauty');
    var chk_boxes = document.getElementsByName('dish');


    which means you can get rid of that entire for-loop

  • 7. You do not need a createError function, just use a variable as an array, and have it keep track of which errors are found. if you want only 1 error, then just change your conditional statements to reflect which error to thro, and then return false.


  • 8. You would be better off using regular expressions for your validation, and the regexp you did use were not the best expressions/usage.


  • 9. Never use "var" inside a loop


  • 10. You can reuse some of your functions if your make them a bit more abstract.


  • 11. Don't use innerHTML


  • 12. If you are going to allow a user to only specify 1 selection (dishes) then you should use radio buttons and not checkboxes


  • There were a few other problems, but fixing the above problems should correct most of them.
    Copy linkTweet thisAlerts:
    @konithomimoSep 17.2008 — here is your code, with the above fixes. there are a few parts that do not seem right . . . addCheckOpts creates radio buttons? you want to delete the newrow if a radio option is changed?

    &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
    &lt;html lang="en"&gt;
    &lt;head&gt;
    &lt;title&gt;validation&lt;/title&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt;

    &lt;script type="text/javascript"&gt;

    var errors_found = [0,0,0,0,0,0];

    var errors = [];
    errors[0]="Namefield has either blank spaces or been left blank. Please fill in.";
    errors[1]="Emailfield has either blank spaces or been left blank. Please fill in.";
    errors[2]="Field has illegal characters. Please fill in letters only.";
    errors[3]="Not a valid email address.";
    errors[4]="Please select an city.";
    errors[5]="Please select at least one favorite dish.";

    var radio_boxes = document.getElementsByName('beauty');
    var chk_boxes = document.getElementsByName('dish');

    function attachHandlers(){
    var the_button = document.getElementById("my_button");
    the_button.onclick=function(){return checkFormFields(this.form);};

    var radio_sel = document.getElementById("radiochoice");
    radio_sel.onclick=addRadioOpts;

    var chkbox_sel = document.getElementById("checkchoice");
    chkbox_sel.onclick=addCheckOpts;

    }

    function addRadioOpts(){

    var newrow = document.createElement("tr");
    newrow.id='newrow';
    var newcell1 = document.createElement("td");
    var newcell2 = document.createElement("td");

    try{
    var newInput1 = document.createElement('&lt;input type="radio" name="movie" size=2 class="textstyle" value="swordfish"&gt;')
    }catch(E){
    var newInput1 = document.createElement('input');
    newInput1.type = "radio";
    newInput1.name = "movie";
    newInput1.size = 2;
    newInput1.className = 'textstyle';
    newInput1.value = 'swordfish';
    }
    var nameText1 = document.createTextNode("Swordfish");

    try{
    var newInput2 = document.createElement('&lt;input type="radio" name="movie" size=2 class="textstyle" value="perfect_stranger"&gt;')
    }catch(E){
    var newInput2 = document.createElement('input');
    newInput2.type = "radio";
    newInput2.name = "movie";
    newInput2.size = 2;
    newInput2.className = 'textstyle';
    newInput2.value = 'perfect_stranger';
    }
    var nameText2 = document.createTextNode("Perfect Stranger");

    newcell1.appendChild(newInput1);
    newcell1.appendChild(nameText1);
    newcell2.appendChild(newInput2);
    newcell2.appendChild(nameText2);

    newrow.appendChild(newcell1);
    newrow.appendChild(newcell2);

    var the_table = document.getElementsByTagName("table")[0];
    var the_label = document.getElementById("target1");
    var my_row = the_label.parentNode.parentNode;


    the_table.insertBefore(newrow, my_row);

    // Not sure what this is for . . . most likely you want to check the checked value to see if you need to do this . . .
    for (var j=0; j&lt;radio_boxes.length; j++)
    {
    radio_boxes[j].onchange=function(){the_table.removeChild(document.getElementById('newrow'));}
    }

    return;
    }


    function addCheckOpts(){
    try{
    var newInput3 = document.createElement('&lt;input type="radio" name="movie" size=2 class="textstyle" value="perfect_stranger"&gt;')
    }catch(E){
    var newInput3 = document.createElement('input');
    newInput3.type = "radio";
    newInput3.name = "choice";
    newInput3.size = 2;
    newInput3.className = 'textstyle';
    newInput3.value = "chicken'n'pasta";
    }
    var nameText3 = document.createTextNode("chicken'n'pasta");

    try{
    var newInput4 = document.createElement('&lt;input type="radio" name="movie" size=2 class="textstyle" value="perfect_stranger"&gt;')
    }catch(E){
    var newInput4 = document.createElement('input');
    newInput4.type = "radio";
    newInput4.name = "choice";
    newInput4.size = 2;
    newInput4.className = 'textstyle';
    newInput4.value = "chicken'n'potatoes";
    }
    var nameText4 = document.createTextNode("chicken'n'potatoes");

    var the_box = document.getElementById("mainchkbox");
    var the_cell = the_box.parentNode;

    the_cell.insertBefore(newInput3, the_box);
    the_cell.insertBefore(newText3, the_box);
    the_cell.insertBefore(newInput4, the_box);
    the_cell.insertBefore(newText4, the_box);

    var chicken_sel = document.getElementById("checkchoice");

    //chicken_sel.onchange=function(){my_table.removeChild(newInput3);} Not sure what this is for
    return; <br/>
    }


    function checkFormFields(f)
    {
    var first_field = document.getElementById("the_name");
    var sec_field = document.getElementById("the_email");
    var the_sel = document.getElementById("myselections");
    var sel_opt = the_sel.options[the_sel.selectedIndex];
    var my_inputs = document.getElementsByTagName("input");

    //Update the errors_found array using the following functions
    checkBlank(first_field.value,0);
    checkBlank(sec_field.value,1);
    checkIllegalChars(first_field.value);
    checkValidEmail(sec_field.value);
    checkSelOpts(sel_opt);
    checkCheckedOpts(chk_boxes);

    //Check the errors
    var error_message = '';
    for(i=0;i&lt;errors_found.length;i++){
    if(errors_found[i] == 1)
    error_message+=errors[i]+'&lt;br&gt;';
    var the_field=document.getElementById("message");
    var message = document.createTextNode(error_message);

    the_field.appendChild(message);

    if(error_message == '')
    f.submit();

    return;
    }

    function checkBlank(the_val,inc){
    for(var i=0; i &lt; the_val.length; i++){
    if ((the_val.charAt(i)!="") &amp;&amp; (the_val.charAt(i)!="t") &amp;&amp; (the_val.length!=0)){
    return true;
    }
    }

    errors_found[inc] = 1;
    return false;
    }

    function checkIllegalChars(theuser_name){
    var name_exp = /[a-zA-Z]+/;

    for(var i=0; i &lt; theuser_name.length; i++)
    {
    the_char = theuser_name.charAt(i);

    if (!name_exp.text(the_char))
    {
    errors_found[2] = 1;
    return false;
    }
    }

    return true;
    }

    function checkValidEmail(user_email, error){
    var my_regexp = /^[w.-]+@([w-]+.)+[a-zA-Z]+$/;

    if (!my_regexp.test(user_email))
    {
    errors_found[3] = 1;
    return false;
    }

    return true;
    }




    function checkSelOpts(city_opts, error){
    if (city_opts!= -1 &amp;&amp; city_opts.value !="none")
    return true;

    errors_found[4] = 1;
    return false;
    }

    function checkCheckedOpts(check_boxes, error){

    for(var i=0; i &lt; check_boxes.length; i++)
    {
    var ones_chkd = check_boxes[i].checked;

    if(!ones_chkd)
    {
    errors_found[5] = 1;
    return false;
    }
    }

    return true;
    }
    &lt;/script&gt;
    &lt;style type="text/css"&gt;
    .formstyle {position: absolute;
    left: 260px;
    top: 75px;
    background-color: darkblue;
    padding-top:150px;
    padding-bottom:50px;
    }

    .textstyle {
    font-family: Arial;
    font-size: 11px;
    color: white;
    }

    #messagestyle {position:absolute;
    left: 75px;
    top: 15px;
    border: solid 2px black;
    color: lightblue;
    }


    &lt;/style&gt;
    &lt;/head&gt;
    &lt;body bgColor="black" onLoad="attachHandlers();"&gt;
    &lt;div class="formstyle"&gt;
    &lt;div id="message"&gt;&lt;/div&gt;
    &lt;table&gt;
    &lt;form action="mailto:[email protected]" method="post"&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="Name" class="textstyle"&gt;Your Name:
    &lt;input type="text" name="Name" id="the_name" size="20"&gt;
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="Email" class="textstyle"&gt;E-mail Address:
    &lt;input type="text" name="Email" id="the_email" size="20"&gt;
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;span class="textstyle"&gt;Please select a city:&lt;/span&gt;
    &lt;select name="city" id="myselections"&gt;
    &lt;option selected="selected"&gt;(none)&lt;/option&gt;
    &lt;option value="Chicago"&gt;Chicago&lt;/option&gt;
    &lt;option value="Atlanta"&gt;Atlanta&lt;/option&gt;
    &lt;option value="D.C."&gt;Wash D.C.&lt;/option&gt;
    &lt;option value="New York"&gt;Chicago&lt;/option&gt;
    &lt;/select&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="beauty" class="textstyle" id="target1"&gt;Who Do You Like More:
    &lt;input type="radio" name="beauty" value="Halle" size="2" id="radiochoice"&gt;Halle Berry
    &lt;input type="radio" name="beauty" value="Beyonce Knowles" size="2"&gt;Beyonce Knowles
    &lt;input type="radio" name="beauty" value="Rosario Dawson" size="2"&gt;Rosario Dawson
    &lt;input type="radio" name="beauty" value="Jessica Alba" size="2" id="breakpoint"&gt;Jessica Alba
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;label for="dish" class="textstyle"&gt;What's Your Favorite Dish:&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="fish" size="2"&gt;Fish&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="chicken" size="2" id="checkchoice"&gt;Chicken&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="sphagetti" size="2" id="mainchkbox"&gt;Sphagetti&lt;br&gt;
    &lt;input type="checkbox" name="dish" value="rice" size="2"&gt;Rice
    &lt;/label&gt;
    &lt;/td&gt;
    &lt;tr&gt;
    &lt;tr&gt;
    &lt;td&gt;
    &lt;input type="button" value="send form" id="my_button"&gt;
    &lt;/td&gt;
    &lt;/tr&gt;
    &lt;/form&gt;
    &lt;/table&gt;
    &lt;/div&gt;

    &lt;/body&gt;
    &lt;/html&gt;
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 18.2008 — here is your code, with the above fixes. there are a few parts that do not seem right . . . addCheckOpts creates radio buttons? you want to delete the newrow if a radio option is changed?
    [/QUOTE]


    Thanks for the code. I'm trying to get it to work and it hasn't done anything yet. I'll go over it line for line.

    Yes, I do want to delete the newrow if the radio option is changed. Any suggestions on that? I did add a function at the end of addRadioOpts() to delete the radio buttons for the first group. For addCheckOpts() I wanted to either add two more radio buttons depending on what the user selects or two more check options, but with the additional check options I wanted only one to be chosen.

    All of your responses are greatly appreciated. I won't be able to get back to this code until Friday night. So if you respond, you'll hear something back then. Thanks?
    Copy linkTweet thisAlerts:
    @banksworld1986authorSep 20.2008 — I read through the code and have a few questions:

    [CODE]
    function checkBlank(the_val,[COLOR="Blue"]inc[/COLOR]){
    for(var i=0; i < the_val.length; i++){
    if ((the_val.charAt(i)!="") && (the_val.charAt(i)!="t") && (the_val.length!=0)){
    return true;
    }
    }

    [COLOR="Blue"]errors_found[inc][/COLOR] = 1;
    return false;
    }
    [/CODE]


    what does errors_found[inc] represent?

    [CODE]
    //Check the errors
    var error_message = '';
    for(i=0;i<errors_found.length;i++){
    if(errors_found[i] == 1)
    error_message+=errors[i]+'<br>';
    var the_field=document.getElementById("message");
    var message = document.createTextNode(error_message);
    [/CODE]


    It looks as if you are looping through the global variable errors_found to check if it has a value. if it does it'll be represented by [COLOR="Blue"]'1'[/COLOR] if not [COLOR="Blue"]'0'[/COLOR]

    If it is represented by value '1', then you loop through each position in the array and replace it with the error message in the 'errors' array. But I don't see where that happens in the code and I also don't see what 'error_message' is displayed...I guess you'll leave that up to me ?

    [CODE]
    function checkValidEmail(user_email, error){
    var my_regexp = /^[w.-]+@([w-]+.)+[a-zA-Z]+$/;

    if (!my_regexp.test(user_email))
    {
    errors_found[3] = 1;
    return false;
    }

    return true;
    }
    [/CODE]


    Not sure why you kept the 'error' parameter here, I don't see it being used in the function at all. In my original code this was being used as a property of the 'errors' object. Like errors[error.val]="foo". You probably didn't intend to do this.

    [CODE]
    try{
    var newInput1 = document.createElement('<input type="radio" name="movie" size=2 class="textstyle" value="swordfish">')
    }catch(E){
    var newInput1 = document.createElement('input');
    newInput1.type = "radio";
    newInput1.name = "movie";
    newInput1.size = 2;
    newInput1.className = 'textstyle';
    newInput1.value = 'swordfish';
    }
    [/CODE]


    With this I guess you were saying that there would be browser compatibility issues so that why you used try & catch...I'm sure that what you meant...not to familiar with that conditional..

    Well...still working on it and thanks for your suggestions...I'll see what I can do.
    ×

    Success!

    Help @banksworld1986 spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.18,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...