Hello. I am new to JavaScript and need to make sure that all of the fields in this form are populated before the submission will go through, otherwise a message needs to popup saying which fields are missing information. Can someone please help. My code so far is:

<html>
<head>

<title>Gia's Web Page</title>

<link type="text/css" rel="stylesheet" href="style3.css" >

</head>

<body>

<!-- Comment: Introduction -->

<a name="introduction"></a>

<h1>This is my <b>Individual Programming Assignment #1</b>.</h1>

<br><br>

<!-- Comment: Purpose -->

<h3><i>This page has been developed by Gia.</i></h3>

<br><br>

<img src="tulip.jpg" style="opacity:0.4;filter:alpha(opacity=40)"
onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" /><img src="tulip2.jpg" style="opacity:0.4;filter:alpha(opacity=40)"
onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100"
onmouseout="this.style.opacity=0.4;this.filters.alpha.opacity=40" />	


<br><br>

<span id="spnWelcome"></span>

<body onLoad="greetUser()">

<script type="text/javascript">

 function greetUser()
    {
        // Prompt the user for their name
        var usersName = prompt("Hi. What is your name?", "");
 
        // Get an object reference to the <span> tag
        var welcomeTag = document.getElementById("spnWelcome");
 
       // Create an array to hold month names
	var monthNames = new Array();
 
	// Populate array with month names
	monthNames[0] = 'January';
	monthNames[1] = 'February';
	monthNames[2] = 'March';
	monthNames[3] = 'April';
	monthNames[4] = 'May';
	monthNames[5] = 'June';
	monthNames[6] = 'July';
	monthNames[7]  = 'August';
	monthNames[8] = 'September';
	monthNames[9] = 'October';
	monthNames[10] = 'November';
	monthNames[11] = 'December';
 
	// Get current date/time
	var today = new Date();
 
	// Get the month number. Notice that this time, I am not adding 1 to the month number, since having a zero base monthNames array works 
	// out perfectly with the fact that getMonth() returns a 0-based month index.
	month = today.getMonth();

	// Get the day of the month
	var day = today.getDate();
 
	// Get the full year
	var year = today.getFullYear();
 
	// Format the date in the following format: MonthName day, year
	var formattedDate = monthNames[month] + ' ' + day + ', ' + year;
 
        // Replace the content of the <span> tag with a personalized message
        welcomeTag.innerHTML = 'Hi ' + usersName + '!!! Welcome to my Website! <br>Today is: ' + formattedDate;
    }



</script>

<br><br>

<script type="text/javascript">

function createOrder()
{

coffee=document.forms[0].coffee;
txt="";
for (i=0;i<coffee.length;++ i)
  {
  if (coffee[i].checked)
    {
    txt=txt + coffee[i].value + " ";
    }
  }
document.getElementById("order").value="You ordered a coffee with " + txt + "and options.";
}

function check(whip)
  {
  document.getElementById("answer").value=whip;
  }

function flavor()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text;
}

</script>



</head>

<body>

<p>What would you like to drink?</p>
<form>
<p>
<input type="checkbox" name="drink" value="coffee">coffee<br />
<input type="checkbox" name="drink" value="tea">tea<br />
<p>
<input type="radio" name="browser" onclick="check(this.value)" value="with milk">With Milk<br />
<input type="radio" name="browser" onclick="check(this.value)" value="extra milk">With Extra Milk<br />
<input type="radio" name="browser" onclick="check(this.value)" value="light milk">With Light Milk<br />
<input type="radio" name="browser" onclick="check(this.value)" value="no milk">No Milk<br />
<br />
Your milk preference is: <input type="text" id="answer" size="20">
<p>

What size would you like?: <input type="text" size="20" value="Enter small, medium or large here" />
<p>
Would you like it hot, cold or blended?: <input type="text" size="20" value="Enter hot, cold or blended here" />
<p>
Would you like sugar?: <input type="text" size="20" value="Enter yes or no here" />
<p>
Select your favorite flavor:
<select id="myList" onchange="flavor()">
	<option></option>
	<option>Vanilla</option>
	<option>Mint</option>
	<option>Butterscotch</option>
</select>
<p>Your favorite flavor is: <input type="text" id="favorite" size="20"></p>
<p>
<input type="button" onclick="formReset()" value="Reset">
<p>
<input type="button" onclick="createOrder()" value="Submit order">
<br /><br />
<input type="text" id="order" size="50">
</form>



<br><br>

<a href="mailto:my_email@yahoo.com">Send e-mail</a>

</body>

</html>

This is a little function I wrote to verify form fields, all you need is an div with the id "error" to take the output.

/**
 * Make sure required fields are set on a form
 * 
 * @param elements   Array of required field IDs
 * @param parentForm ID of the form
 * @param setvalTar  ID of a hidden field to be set(optional)
 * @param setval  	 Value for setvalTar
 */
function verifyForm(elements,parentForm,setvalTar,setVal)
{
	var valid = true;
	for(i=0;i<(elements.length);i++){
		$(elements[i]).className = ($(elements[i]).value == "")?'txtError':null;
		valid = ($(elements[i]).value == "")?false:valid;
	}
	$('error').style.display = (valid)?'none':'';
	$('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
	if(setvalTar != null && setVal != null)
		setValue(setvalTar,setVal);
	if(parentForm != null && valid)
		 $(parentForm).submit();
	else return valid;
}

Then in an html form you would have something like

<div id='error'></div>
<form action="blah.php" method="post">
    <input type="text"  name="fname" id="fname" />
    <input type="text" name="lname" id="lname" />
    <input type="button" onclick="if(verifyForm(['fname','lname'])){window.location='test.php';}" />
</form>

Almost forgot, for that to work you need this little line, I always forget it :)

function $(id){return document.getElementById(id);}

> This is a little function I wrote to verify form fields, all you need is an div with the id "error" to
> take the output.

A required addition to that script would be checking whether the element really exists and trimming the form values before comparing them with an empty string so that I can't get away by keying in just a few whitespace characters.

Comments
almost forgot that, thanks

Good looking out ~s.o.s~, maybe something along the lines of this.

/**
 * Make sure required fields are set on a form
 * 
 * @param elements   Array of required field IDs
 * @param parentForm ID of the form
 * @param setvalTar  ID of a hidden field to be set(optional)
 * @param setval       Value for setvalTar
 */
function verifyForm(elements,parentForm,setvalTar,setVal)
{
    var valid = true;
    for(i=0;i<(elements.length);i++){
        if($(elements[i]))
        {
            $(elements[i]).value = $(elements[i]).value.replace(/^\s(.*)/,'$1');
             $(elements[i]).className = ($(elements[i]).value == "")?'txtError':null;
            valid = ($(elements[i]).value == "")?false:valid;
        }
        else valid = false;
    }
    $('error').style.display = (valid)?'none':'';
    $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
    if(setvalTar != null && setVal != null)
        setValue(setvalTar,setVal);
    if(parentForm != null && valid)
         $(parentForm).submit();
    else return valid;
}

Aside from that, I also forgot to mention that you must have a CSS class that is applied to the textbox if there is an error, in this case it is called txtError but you can name it whatever you like and just change the code.

A tad inefficient considering that you do the $('someId') thing again. It is in the end a call to document.getElementById() which basically traverses the entire in-memory DOM of the entire HTML document. Cache / store a reference to your Javascript objects whenever possible.

A better way of accessing form elements would be by using their name. Assuming that you need to access the value of a form control named 'txtName' , forms["formName"].elements["txtName"].value should do the trick. Make your function accept the form object as well.

Your regex trims only leading whitespaces (you can key in that regex at the Firefox error console and see for yourself). A complete regex would be yourStr.replace(/(^\s+)|(\s+$)/g, '') Other than the things mentioned above, you are good to go. :-)

This sort of turned into a thread about my function but would this work or no?

/**
 * Make sure required fields are set on a form
 * 
 * @param elements   Array of required field IDs
 * @param parentForm ID/Name of the form
 * @param setvalTar  ID of a hidden field to be set(optional)
 * @param setval       Value for setvalTar
 */
function verifyForm(elements,parentForm,setvalTar,setVal)
{
    var valid = true;
    parent = $(parentForm);
    if(!parent) parent = forms[parentForm];
    for(i=0;i<(elements.length);i++){
        if(parent.action) //will this work to make sure it's a form?
           elem = parent.elements[elements[i]];
        else
           elem = $(elements[i]);
        if(elem)
        {
            elem.value = elem.value.replace(/(^\s+)|(\s+$)/g, '');
            elem.className = (elem.value == "")?'txtError':null;
            valid = (elem.value == "")?false:valid;
        }
        else valid = false;
    }
    $('error').style.display = (valid)?'none':'';
    $('error').innerHTML = (valid)?'':'<b>Please fill in the required fields</b>';
    if(setvalTar != null && setVal != null)
        setValue(setvalTar,setVal);
    if(parentForm != null && valid)
         $(parentForm).submit();
    else return valid;
}

Yes, except that you don't need to get the form element by ID. In the calling function, instead of passing the form ID, pass the form object. verifyForm(..., this.form);

Well I did that as a name or ID so they could either give a form or some other element as a parent (which realizing now would break the submit() call)

This article has been dead for over six months. Start a new discussion instead.