Solved

Empty String Function

Posted on 2006-10-24
7
2,486 Views
Last Modified: 2008-02-20
I am trying to figure out how I can add a JavaScript function that loops through each input field in the form and tests for an empty string.

Here is my code:

<html>
<head><title>Validation Form</title>
</head>

<SCRIPT>
function SymError()
{
  return true;
}

window.onerror = SymError;

var SymRealWinOpen = window.open;

function SymWinOpen(url, name, attributes)
{
  return (new Object());
}

window.open = SymWinOpen;

function checkYear(objForm){
     var objFormField=objForm.elements['txtYear']
     if(objFormField.value.length != 2 &&  objFormField.value.length != 4){
          alert("The credit card year must be either two or four characters long!");
          objFormField.focus()
          return false;
     }
     var theYear = objFormField.value;
       var theMonth=objForm.elements['cardMonth'].value;
     var datNow = new Date();
       var thisMonth=datNow.getMonth()+1;
     var thisYear = datNow.getFullYear()
     if(theYear.length==2){
          thisYear = "" + thisYear
          theYear = thisYear.substring(0,2) + theYear
     }
     if(theYear*1<thisYear){
          alert("The card has expired!");
          objFormField.focus();
          return false;
     }
      else if(theYear*1==thisYear && theMonth<thisMonth){
          alert("The card has expired!");
          objFormField.focus();
          return false;
            }
     return true;
}


function checkForZero(field)
{
    if (field.value == 0 || field.value.length == 0) {
        alert ("This field can't be 0!");
        field.focus(); }
    else
        calculatePayment(field.form);
}

function cmdCalc_Click(form)
{
    if (form.price.value == 0 || form.price.value.length == 0) {
        alert ("The Price field can't be 0!");
        form.price.focus(); }
    else if (form.ir.value == 0 || form.ir.value.length == 0) {
        alert ("The Interest Rate field can't be 0!");
        form.ir.focus(); }
    else if (form.term.value == 0 || form.term.value.length == 0) {
        alert ("The Term field can't be 0!");
        form.term.focus(); }
    else
        calculatePayment(form);
}

function calculatePayment(form)
{
    princ = form.price.value - form.dp.value;
    intRate = (form.ir.value/100) / 12;
    months = form.term.value * 12;
    form.pmt.value =

Math.floor((princ*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100;
    form.principle.value = princ;
    form.payments.value = months;
}

function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
  {alert(alerttxt);return false}
else {return true}
}
}

function validate_form(thisform) {
     with (thisform) {
          if (validate_email(email,"Not a valid e-mail address!")==false) {
               email.focus();
               return false;
          }
     }
}
var whichSubmit=0
function validationAll(form_elem) {
     if(whichSubmit==0 && (validate_form(form_elem) == false || checkYear(form_elem)

== false) ) {
          return false;
          }
     else if (checkYear(form_elem) == false || validate_form(form_elem) == false) {
          return false;
     } else {
          return true;
     }
}
//-->
</SCRIPT>
<body bgcolor="aqua">
</head><body>
<font size="-1" face="Verdana, Arial, Helvetica, sans-serif">
<h2 style="text-align:center">Validation Form</h2>
<p>
<hr style="color: blue; background-color: blue: 6; width:100%"/>
<p><b></b><p>

<form action="validation2.htm" onsubmit="return validationAll(this);">

<table cellspacing="2" cellpadding="2" border="0">
<tr>
    <td align="right">First Name</td>
    <td><input type="text" name="Name"></td>
</tr><br>
<tr>
    <td align="right">Last Name</td>
    <td><input type="text" name="Address"></td>
</tr><br>
<tr>
    <td align="right">City</td>

    <td><input type="text" name="City"></td>
</tr><br>
<tr>
<tr>
    <td align="right">State</td>
    <td>

        <select name="State">
          <option value="" ></option>selected>[choose yours]
          <option value="AL"/>Alabama
          <option value="AK"/>Alaska
          <option value="AZ"/>Arizona
          <option value="AK"/>Arkansa
          <option value="CA"/>California
          <option value="CO"/>Colorado
          <option value="CT"/>Connecticut
          <option value="DE"/>Delaware
          <option value="DC"/>District of Columbia
          <option value="FL"/>Florida
          <option value="GA"/>Georgia
          <option value="HA"/>Hawaii
          <option value="ID"/>Idaho
          <option value="IL"/>Illinois
          <option value="IN"/>Indiana
          <option value="IA"/>Iowa
          <option value="KS"/>Kansas
          <option value="KY"/>Kentucky
          <option value="LA"/>Louisiana
          <option value="ME"/>Maine
          <option value="MD"/>Maryland
          <option value="MA"/>Massachusetts
          <option value="MI"/>Michigan
          <option value="MN"/>Minnesota
          <option value="MS"/>Mississippi
          <option value="MO"/>Missouri
          <option value="MT"/>Montana
          <option value="NE"/>Nebraska
          <option value="NV"/>Nevada
          <option value="NH"/>New Hampshire
          <option value="NJ"/>New Jersey
          <option value="NM"/>New Mexico
          <option value="NY"/>New York
          <option value="NC"/>North Carolina
          <option value="ND"/>North Dakota
          <option value="OH"/>Ohio
          <option value="OK"/>Oklahoma
          <option value="OR"/>Oregon
          <option value="PA"/>Pennsylvania
          <option value="PR"/>Puerto Rico
          <option value="RI"/>Rhode Island
          <option value="SC"/>South Carolina
          <option value="SD"/>South Dakota
          <option value="TN"/>Tennessee
          <option value="UT"/>Utah
          <option value="VT"/>Vermont
          <option value="VI"/>Virgin Islands
          <option value="VA"/>Virginia
          <option value="WI"/>Wisconsin
          <option value="WY"/>Wyoming
       </select>

     </td>

</tr>
   <td align="right">Zip</td>
    <td><input type="text" name="Zip"></td>
</tr><br>
<tr>
    <td align="right">Telephone number</td>
    <td><input type="text" name="Telephone number"size="10"></td>
</tr><br>

<tr>
    <td align="right">Email</td>
    <td><input type="text" name="email"size="30"><input type="submit" value="Verify"

onclick="whichSubmit=0"><input type="reset"value="Reset"/></tr><br>
<tr>
    <td align="right">Date of Birth</td>
    <td><input type="text" name="Date of Birth"maxlength="10" size="15"></td>
</tr><br>
<p>
<table><tr>
    <tr>

    <td align="Center" >
    <fieldset>
    <legend> Select Credit Card Type (check one) </legend>
    <label for="r1"><input type="radio" name="group1"
     id="r1" value="1"/> Visa</label>
    <label for="r1"><input type="radio" name="group1"
     id="r2" value="1"/> Master Card</label>
    <label for="r1"><input type="radio" name="group1"
     id="r3" value="1"/> American Express</label>

    <label for="r1"><input type="radio" name="group1"
     id="r4" value="1"/> Discover </label>
     </fieldset>
    </td>
</tr></table>

<tr>
    <td align="right">Credit Card Number</td>
    <td><input type="text" name="Credit Card Number"size="16"/></td>
</tr>

<tr>

<td valign="bottom">
<td align="right">Month</td>
<select name="cardMonth">
<option value="01"/> 01
<option value="02"/> 02
<option value="03"/> 03
<option value="04"/> 04
<option value="05"/> 05
<option value="06"/> 06

<option value="07"/> 07
<option value="08"/> 08
<option value="09"/> 09
<option value="10"/> 10
<option value="11"/> 11
<option value="12"/> 12
</select>
<tr>
    <td align="right">Year</td>

    <td><input type="text" name="txtYear"maxlength="4" size="2"></td>

<input type="submit" value="Submit" onclick="whichSubmit=1"/>
<input type="reset" value="Reset"/>
</tr><br>

<hr style="color: blue; background-color: blue: 6; width:100%"/>
<p><b></b><p>


<table>
<tr>
<td align="center"/>
</tr>
<form id="MortgageCalculator"/>

<table width="250" border="5" bgcolor="Blue" cellpadding="2">
<tr>
<td colspan="2" align="CENTER">
<b><font size="+2" color="Aqua"/>M<font size="+2"/>ORTGAGE <font size="+2"/>C<font

size="+2"/>alculator</b>
</td>
</tr>

<tr>
<td colspan="2" width="50%">
<table border="0" cellpadding="2">

<tr>
<td colspan="2"><b>Mortgage Data:</b></td>

</tr>
<td align="RIGHT">House Price:</td>
<td>
<input
    type="TEXT"
    name="price"
    value="200000"
    size="7"
    onblur="checkForZero(this)"
    onchange="checkForZero(this)"/>
</td>
</tr>

<tr>
<td align="RIGHT">Down Payment:</td>
<td>

 <input
    type="TEXT"
    name="dp"
    value="0"
    onchange="calculatePayment(this.form)"
    size="7"/>
</td>

</tr>

<tr>
<td align="RIGHT">Annual Interest Rate:</td>
<td>
<input
    type="TEXT"
    name="ir"
    value="7.5"
    size="4"
    onblur="checkForZero(this)"
    onchange="checkForZero(this)"/>
%
</td>
</tr>

<tr>
<td align="RIGHT">Term:</td>

<td>

<input
    type="TEXT"
    name="term"
    value="30"
    size="4"
    onblur="checkForZero(this)"
    onchange="checkForZero(this)"/>
Years
</td>
</tr>


<tr>
<td>

<table border="0" cellpadding="2">

<tr>
<td colspan="2"><b>Results:</b></td>

</tr>
<td align="RIGHT">Mortgage Principle:</td>

<td>

<input
    type="TEXT"
    name="principle"
    size="7"/>

</td>
</tr>
<tr>
<td align="RIGHT">Total Payments:</td>
<td>
<input
    type="TEXT"
    name="payments"
    size="7"/>
</td>
</tr>

<tr>

<td align="RIGHT">Monthly Payment:</td>

<td>
<input
    type="TEXT"
    name="pmt"
    size="7"/>
</td>
</tr>
</table>



<tr>
<td align="CENTER" colspan="2">
<input
    type="BUTTON"
    name="cmdCalc"
    value="Calculate"
    onclick="cmdCalc_Click(this.form")/>

</td>
</tr>
</table>
 </html>
0
Comment
Question by:mayan1
7 Comments
 
LVL 5

Expert Comment

by:daohailam
ID: 17795049
var f = document.getElementsByTagName('input');
for (i in f) {
  if (f[i].type != 'text') continue;
  if (f[i].value == '') {
     f[i].focus();
     break;
  }
}
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 17795071
Perhaps use something like this:
http://formassembly.com/wForms/
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 17795944
I would add an alert, to let the user know what happened

var f = document.getElementsByTagName('input');
for ( var i = 0; i < f.length; ++i ) {
  if ( f[ i ].type == 'text') {
    if (f[i].value == '') {
       f[i].focus();
       alert( 'Empty input field' );
       break;
    }
  }
}
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 41

Expert Comment

by:HonorGod
ID: 17795990
mplungjan - really cool link.  Thanks!
0
 

Author Comment

by:mayan1
ID: 17796860
Honor God,
Is there anything else I need to do besides add this function? I am a little confused. Can you show me in my code?
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 17803729
Just change
function validate_form(thisform) {
     with (thisform) {
          if (validate_email(email,"Not a valid e-mail address!")==false) {
               email.focus();
               return false;
          }
     }
}

to


function validate_form(thisform) {
  if (validate_email(thisform.email,"Not a valid e-mail address!")==false) {
    email.focus();
    return false;
  }
  var f = thisform.elements;
  for ( var i = 0; i < f.length; ++i ) {
    if ( f[ i ].type == 'text') {
      if (f[i].value == '') {
         f[i].focus();
         alert( 'Empty input field' );
         return false;
      }
    }
  }
  return true;
}


I would also change

function validationAll(form_elem) {
     if(whichSubmit==0 && (validate_form(form_elem) == false || checkYear(form_elem)

== false) ) {
          return false;
          }
     else if (checkYear(form_elem) == false || validate_form(form_elem) == false) {
          return false;
     } else {
          return true;
     }
}
to


function validationAll(form_elem) {
  return validate_form(form_elem) && checkYear(form_elem)
}

since you test all regardless of what submit was clicked
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 17803771
or more logical

change

function checkYear(objForm){
     var objFormField=objForm.elements['txtYear']
to

function checkYear(objFormField){


and have



function validationAll(thisform) {

  if (validate_email(thisform.email,"Not a valid e-mail address!")==false) {
    email.focus();
    return false;
  }
  if (!checkYear(thisform.txtYear') {
    return false;
  }
  var f = thisform.elements;
  for ( var i = 0; i < f.length; ++i ) {
    if ( f[ i ].type == 'text') {
      if (f[i].value == '') {
         f[i].focus();
         alert( 'Empty input field' );
         return false;
      }
    }
  }
  return true;
}

instead of two validation functions
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now