Form submission using JavaScript

Hello all,

Firstly, a thanks to Sitepoint and their authors or for writing incredibly useful books. I’m a massive fan.

I’m in a spot of bother, I’m trying to create a form that pops-up a new window. Within that window will contain the user’s name, their location and a score all of which will have been entered within the form.

Now, this will seem weird but I am trying to do this in 100% JavaScript. I know using Jquery library functions or some server side language will make this 100 times easier, but I want to get my knowledge up on the basics first, which is why I’m going for the 100% JavaScript route. I know it can be done purely in JS, I just need some (probably a lot) of direction.

Just to reiterate what I’m attempting to achieve here:

1)User enters NAME into a field
2)User selects their location from a menu
3)The user rates sections of the site on a scale of 1 to 5
4)When the user submits the form, and if the user has rated lowly (say, less than 60%) then a new windows will pop-up, this window will display their name, location and overall score as a percentage. If they have rated higher than 60%, I just want to show an alert box saying “thanks”.

I do apologies if this thread appears as a “please do my work”, but I’m trying to as specific as possible so you can understand my very jumbled thought process.

Here is my very poor attempt at JavaScript (my HTML is underneath this).

function submit()
{


var maximum = 20

var knowledge1 = document.getElementById('knowledgebase').value;
var knowledge2 = document.getElementById('knowledgebase2').value;
var knowledge3 = document.getElementById('knowledgebase3').value;
var knowledge4 = document.getElementById('knowledgebase4').value;



var total = knowledge1 + knowledge2 + knowledge3 + knowledge4

var percentage = Math.round((total * 100)/maximum);


if (percentage < 60)

{



newWindow = window.open('','welcome','width=600,height=400, menubar=no, status=yes, toolbar=no, scrollbars=yes');

newWindow.document.write("<html>")
newWindow.document.write("<head><title>
Complaints</title></head><body>")
					
//remember to sanitise quotes
newWindow.document.write('<style type="text/css"> body { background-color: #c7c8e7; } h1 { font-family: arial;  color: #443266; text-align: center; font-size: 175%; font-weight: bold; background-color:d0d0ec;} p { font-family: arial; text-align: center; }   .buttonarea { text-align: center; background-color:#8C489F; padding: 4px; } .buttonarea input { background: #443266; border: 1px solid #ffffff; color: #ffffff; padding: 5px; font-weight: bold; } </style>')


newWindow.document.write("<h1>COMPLAINTS PAGE</h1>")

 newWindow.document.write("<p><strong>Your Name</strong>: " + "<br /><strong>Your Location</strong>: "  "<br /> <strong>Overall, you gave us a score of:</strong> " + percentage + "%.<br /><br />We are sorry to hear you didn't like our site</p>");

newWindow.document.write('</body>');
newWindow.document.write('</html>');
newWindow.document.write('<form>');
newWindow.document.write('<div class="buttonarea"><input type="button" class="submit" value="Print" onclick="window.print();return false;" /></div>') 
newWindow.document.write("</form>")

}			
	return false;				
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
  <head>
    <title>Feedback</title>
    <link href="styles.css" rel="stylesheet" type="text/css" />
    <meta http-equiv="content-type"
        content="text/html; charset=utf-8" />
    
</head>
  <body>
    <div id="wrapper">
 
      <div id="header">
	  <h1>Hello</h1>
	  </div>
	  
	  <div id="content">
	  
	  <h2>Feedback</h2>

	  <p>rate us!</p>
	 
	 
	  <div id="feedbackform">       
<form action="" method="post" class="contact"> 
<fieldset>
<legend><ins>F</ins>eedback Form</legend> 
<div>
<label for="contactname" class="fixedwidth">Contact Name</label>
<input type="text" name="contactname" id="contactname"/>
</div>
 
 
<div>
<label for="region" class="fixedwidth">What region are you in?</label>
<select name="region" id="region">

<option value="Europe">Europe</option>
<option value="Asia">Asia</option>
<option value="North America">North America</option>
<option value="South America">South America</option>
<option value="Africa">Africa</option>
</select>
</div>
 
<br />

<p>Please rate each informative section on a scale of 1 to 5. Five being the best, while one is the worst</p>
 
<div>
<label for="knowledgebase" class="fixedwidth">Knowledge base homepage</label>

<select name="knowledgebase" id="knowledgebase">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
 
<div>

<label for="knowledgebase2" class="fixedwidth">Knowledge base history</label>
<select name="knowledgebase2" id="knowledgebase2">
<option>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>

 
<div>
<label for="knowledgebase3" class="fixedwidth">Knowledge base present</label>
<select name="knowledgebase3" id="knowledgebase3">
<option>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>

</select>
</div>
 
<div>
<label for="knowledgebase4" class="fixedwidth">Knowledge base future</label>
<select name="knowledgebase4" id="knowledgebase4">
<option>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
 
<br />

<div class="buttonarea">

<input type="submit" value="Submit Feedback!"/> 
</div>
 
	   
 
</fieldset>
</form>
</div> <!--feedbackform-->
	 
	 
	  
	   </div><!--content-->
	  
	  
	  <div id="nav">
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About Us</a></li>

		  <li><a href="knowledge.html">Knowledge Base</a></li>
		  <li><a href="resources.html">Resources</a></li>
          <li><a href="contact.html">Contact Us</a></li>
		  <li class="visiting"><a href="feedback.html">Feedback</a></li>
          
		  </ul>
      </div><!-- nav -->
	  
	  
	  
	  <div id="footer">

	  &copy;  All rights reserved. | Twitter | Facebook | Blogger
	  </div><!-- footer -->
	  
	  </div><!--wrapper-->
        
  </body>
</html>

Some basic tips:

How do you intend to attach the script to the form. The standard technique is to gain a reference to the form element, commonly by placing a unique identifier on it, and to associate the function with the forms onsubmit event.


var form = document.getElementById('feedback');
form.onsubmit = submit;

Since you already have an identified div wrapping the form, you don’t need to identify the form, as you can get to it without too much trouble.


var wrapper = document.getElementById('feedbackform'),
    form = wrapper.getElementsByTagName('form')[0];
form.onsubmit = submit;

For the rest of the script, you will do well to run it through jslint.com so that common coding problems.

After sorting those out, your script can remove the id attributes within the form, because you have the form.elements collection that can be more reliably used instead.

For example:


var knowledge1 = this.elements.knowledgebase.value;

But you’re wanting to use those values as numbers, not strings, so cast them to a Number.


var knowledge1 = Number(this.elements.knowledgebase.value);

But what happens if no number is selected? Do you use some kind of error routine?


var knowledge1 = Number(this.elements.knowledgebase.value);
if (isNaN(knowledge1)) {
    // do error stuff
}

I had to change the layout of your code - moving the script into the head of the document and changing the doc.write method to sort out the tangle. I also re-jigged the calculation of the percentages. The submit button is just a button. If you want to submit the form you will need to add suitable attributes to the <form> tag.

You will note that I have changed the knowledge1 etc. strings to numbers to allow the arithmetic to function. I have also selected the zero value for each of the <select> tags so that submitting the form without making a selection returns zero percent.

You should check that the window is not already in existence before creating it.

The following script and HTML work, but you will need to adjust it to meet your own needs.


<script type="text/javascript">
<!--
function submitForm()
{ var maximum = 5;
  var knowledge1 = parseInt(document.getElementById('knowledgebase').value);
  var knowledge2 = parseInt(document.getElementById('knowledgebase2').value);
  var knowledge3 = parseInt(document.getElementById('knowledgebase3').value);
  var knowledge4 = parseInt(document.getElementById('knowledgebase4').value);
 // 
  var total = knowledge1+knowledge2+knowledge3+knowledge4;
 // get average of four scores 
  var avg=total/4;
  var percentage = Math.round(avg/maximum*100);
 //
 if (percentage < 60)
  { var build='<html>\
<head>\
<title>Complaints<\\/title>\
';
   build+='<style type="text/css">\
 body { background-color: #c7c8e7; font-family: arial; text-align: center; }\
';
   build+='h1 { font-family: arial;  color: #443266; text-align: center; font-size: 175%; font-weight: bold; background-color:d0d0ec;}\
';
   build+='\\.buttonarea { text-align: center; background-color:#8C489F; padding: 4px; }\
';
   build+='\\.buttonarea input { background: #443266; border: 1px solid #ffffff; color: #ffffff; padding: 5px; font-weight: bold; }\
<\\/style>\
<\\/head>\
' 
   build+='<body>\
\\/\\/remember to sanitise quotes\
';
   build+='<h1>COMPLAINTS PAGE<\\/h1>\
<p><strong>Your Name<\\/strong><\\/p>\
';
   build+='<p><strong>Your Location<\\/strong><\\/p>\
';
   build+='<p><strong>Overall, you gave us a score of:<\\/strong>'+percentage+'%.<\\/p>\
';
   build+='<p>We are sorry to hear you didn\\'t like our site<\\/p>\
';
   build+='<form>\
<div class="buttonarea">\
<input type="button" class="submit" value="Print" onclick="window.print();return false;" \\/>\
<\\/div>\
<\\/form>\
';
   build+='<\\/body>\
<\\/html>\
';
 // open new window  
   var newWindow = window.open('','welcome','width=600,height=400, menubar=no, status=yes, toolbar=no, scrollbars=yes');
 // write to new window
   newWindow.document.write(build);
   newWindow.document.close();  
  }         
    return false;            
}
//-->
</script>



<!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">

<head>

<title>Feedback</title>

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

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

</head>

<body>

<div id="wrapper">
  <div id="header">
    <h1>Hello</h1>
  </div>
  <div id="content">
    <h2>Feedback</h2>
    <p>rate us!</p>
    <div id="feedbackform">
      <form action method="post" class="contact">
        <fieldset>
        <legend><ins>F</ins>eedback Form</legend>
        <div>
          <label for="contactname" class="fixedwidth">Contact Name</label>
          <input type="text" name="contactname" id="contactname" size="20" />
        </div>
        <div>
          <label for="region" class="fixedwidth">What region are you in?</label>
          <select name="region" id="region">
          <option value="Europe">Europe</option>
          <option value="Asia">Asia</option>
          <option value="North America">North America</option>
          <option value="South America">South America</option>
          <option value="Africa">Africa</option>
          </select>
        </div>
        <p><br />
        Please rate each informative section on a scale of 1 to 5. Five being 
        the best, while one is the worst</p>
        <div>
          <label for="knowledgebase" class="fixedwidth">Knowledge base homepage</label>
          <select name="knowledgebase" id="knowledgebase">
          <option value="0" selected>Select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          </select>
        </div>
        <div>
          <label for="knowledgebase2" class="fixedwidth">Knowledge base history</label>
          <select name="knowledgebase2" id="knowledgebase2">
          <option value="0" selected>Select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          </select>
        </div>
        <div>
          <label for="knowledgebase3" class="fixedwidth">Knowledge base present</label>
          <select name="knowledgebase3" id="knowledgebase3">
          <option value="0" selected>Select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          </select>
        </div>
        <div>
          <label for="knowledgebase4" class="fixedwidth">Knowledge base future</label>
          <select name="knowledgebase4" id="knowledgebase4">
          <option value="0" selected>Select</option>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
          <option value="4">4</option>
          <option value="5">5</option>
          </select>
        </div>
        <div class="buttonarea">
          <br />
          <input type="button" value="Submit Feedback!" onclick="submitForm()" />
          </div>
        </fieldset>
        </form>
        </div>
        <!--feedbackform-->
      </div>
      <!--content-->
      <div id="nav">
        <ul>
          <li><a href="index.html">Home</a></li>
          <li><a href="about.html">About Us</a></li>
          <li><a href="knowledge.html">Knowledge Base</a></li>
          <li><a href="resources.html">Resources</a></li>
          <li><a href="contact.html">Contact Us</a></li>
          <li class="visiting"><a href="feedback.html">Feedback</a></li>
        </ul>
      </div>
      <!-- nav -->
      <div id="footer">
        © All rights reserved. | Twitter | Facebook | Blogger
      </div>
      <!-- footer -->
    </div>
    <!--wrapper-->

</body>

</html>


Oh my goodness, I was only expecting some guidance and received some truly exceptional help!

Both of your posts helped me tremendously, I now have a basic working form using 100% JavaScript.

Thank you very much