I am a Computing teacher trying to stay one step ahead of my pupils whom are working on a assessment to with validating web forms using HTML and JavaScript. So far, I have managed to do the following but can no longer move forward:
<head>
<title>Exam entry</title>
<script language="javascript" type="text/javascript">
function validateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+='You must enter your name';
document.ExamEntry.name.focus();
document.getElementById("name").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+=' You must enter the subject';
document.ExamEntry.subject.focus();
document.getElementById("subject").style.color="#FF0000";
result = false;
}
if (document.ExamEntry.examnumber.value=="") {
msg+=' You must enter the examination number';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000";
result = false;
}
if(document.getElementById("examnumber").value.length!=4)
{
msg+='You must have exactly 4 digits in the examination number textbox';
document.ExamEntry.examnumber.focus();
document.getElementById("examnumber").style.color="#FF0000"
result = false;
}
function checkRadio() {
var user_input = "";
var len = document.ExamEntry.entry.length;
var i;
for (i=0;i< len;i++) {
if (document.ExamEntry.entry[i].length.checked) {
user_input = document.ExamEntry.entry[i].value;
break;
}
}
if (msg==""){
return result;
}
else
{
alert(msg);
return result;
}
}
function resetForm()
{
document.getElementById('ExamEntry').reset();
document.getElementById("name").style.color="#000000";
document.getElementById("subject").style.color="#000000";
document.getElementById("examnumber").style.color="#000000";
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name='ExamEntry' method='post' action='success.html'>
<table width='50%' border='0'>
<tr>
<td id='name'>Name</td>
<td><input type='text' name='name' /></td>
</tr>
<tr>
<td id='subject'>Subject</td>
<td><input type='text' name='subject' /></td>
</tr>
<tr>
<td id='examnumber'>Examination Number</td>
<td><input type='text' name='examnumber'></td>
</tr>
<tr>
<td id='entry'>Level of Entry</td>
<td><input type='radio' name='entry' value='gcse'>GCSE<BR></td>
<td><input type='radio' name='entry' value='as'>AS<BR></td>
<td><input type='radio' name='entry' value='a2'>A2<BR></td>
</tr>
<tr>
<td><input type='submit' name='Submit' value='Submit' onclick='return (validateForm());'></td>
<td><input type='reset' name='Reset' value='Reset' onclick=' (resetForm());'></td>
</tr>
</table>
</form>
</body>
What I want to do and what I am trying to do are two different things and it's now hit the point where I am banging my head against a brick wall.
What I WANT to do is be able to:
Extend the Javascript code to make sure that the user’s examination number is exactly 4 digits.
Add a set of radio buttons to the form to accept a level of entry such as GCSE, AS or A2. Write a function that displays the level of entry to the user in an alert box so that the level can be confirmed or rejected.
Can anyone help me before I totally lose the plot?
It's been a long time I have tried pure JS. It's a pleasure to try it out anytime though. So, someone's lukcy and I had some free time. I am a very tiny bit OCD when it comes to coding and I ended up cleaning a lot of your code, such as
Always enclose HTML attributes in double quotes - not a hard rule though.
Always close the input attributes - /> - not a hard rule though.
Define your elements and resue where needed in JS
Alwayst try and keep your JS separate from HTML - it's a good practice.
And follow the good old basics
As a result, here we go:
Demo: Fiddle
HTML:
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="#">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="examnumber">Examination Number</td>
<td><input type="text" name="examnumber" /></td>
</tr>
<tr>
<td id="entry">Level of Entry</td>
<td><input type="radio" name="entry" value="gcse" />GCSE<BR></td>
<td><input type="radio" name="entry" value="as" />AS<BR></td>
<td><input type="radio" name="entry" value="a2" />A2<BR></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" onclick="resetForm();"></td>
</tr>
</table>
</form>
JS:
var form = document.forms['ExamEntry'];
var iName = form.elements['name'];
var iSubject = form.elements['subject'];
var iExamNumber = form.elements['examnumber'];
var iLevel = form.elements['entry'];
function validateForm() {
var result = true;
var msg = "";
if (iName.value=="") {
msg+='You must enter your name';
iName.focus();
iName.style.color="#FF0000";
result = false;
} else if (iSubject.value=="") {
msg+=' You must enter the subject';
iSubject.focus();
iSubject.style.color="#FF0000";
result = false;
} else if (iExamNumber.value=="" || !/^\d{4}$/.test(iExamNumber.value)) {
msg+=' You must enter a valid examination number';
iExamNumber.focus();
iExamNumber.style.color="#FF0000";
result = false;
} else if(!checkEntry()) {
msg+=' You must select a level';
result = false;
} else {
var cfm = confirm("You have selected " + checkEntry() + ". Are you sure to punish yourself?");
if (!cfm) {
result = false;
}
}
if (!result && msg != "") alert (msg);
return result;
}
function checkEntry() {
for (var i=0; i<iLevel.length; i++) {
if (iLevel[i].checked) {
return iLevel[i].value.toUpperCase();
}
}
return false;
}
function resetForm() {
form.reset();
iName.style.color="#000000";
iSubject.style.color="#000000";
iExamNumber.style.color="#000000";
}
form.onsubmit = validateForm;
form.onreset = resetForm;
First you added the function checkRadio inside of function validateForm
Also, this line
if(document.getElementById("examnumber").value.length!=4)
actually points to this piece of html
<td id='examnumber'>Examination Number</td>
The td element can't hold values... You need to change the line to this:
if (document.ExamEntry.examnumber.value.length!=4) {
This jsfiddle should help you out...
Related
Why number validation is not working in following case.
I'd tried with checking type of value
if(typeof value!=='number'){}
I'd tried with checking if value is less than 1. The value of variable is 0 by default
if(parseInt(value)<1){}
Following snippet is working fine, now I want to add additional requirement, check if user has entered number or not and stop further process alerting number if text has been detected.
It is checking null value, working fine with null value, but what is the wrong with typeof and less than 1.
I'd added the block of code as comment which is not working.
First validation from the comment block is it return false, even we enter number in field.
Second validation from the comment block is partially working, but it has to alert message and break the process, but it is giving NaN result.
window.onload=function(){
bk_issue();
}
function bk_issue(){
document.getElementById('btn_iss').onclick=function(){
if(document.querySelectorAll('input[name="book"]:checked').length===0){
alert('Please check at least one book');
return false;
}
if(document.querySelectorAll('input[name="std"]:checked').length===0){
alert('Please check at least one student or staff');
return false;
}
else{
var ttl_qnt = document.querySelector('input[name="book"]:checked').getAttribute('data-id');
var std = document.querySelectorAll('input[name="std"]:checked');
var iss_qnt=0;
for (var i=0;i<std.length;i++){
var value = std[i].closest('tr').getElementsByTagName('td')[2].querySelector('.qnt').value;
if(value===''){
var std_qnt = 0;
alert('Please fill book quantity in checked student field');
return false;
}
// This validation is not working
/* if(typeof value!=='number'){
var std_qnt = 0;
alert('Please type number only');
return false;
}
if(parseInt(value)<1){
var std_qnt = 0;
alert('Please type number only');
return false;
}*/
else{
var std_qnt = std[i].closest('tr').getElementsByTagName('td')[2].querySelector('.qnt').value;
}
iss_qnt += parseInt(std_qnt);
}
alert(iss_qnt);
}
}
}
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Select</th><th>Book</th><th>Qnt</th>
</tr>
<tr>
<td><input type='radio' name='book' value='1' data-id='20' /></td><td>Social Experiment</td><td>20</td>
</tr>
<tr>
<td><input type='radio' name='book' value='1' data-id='12' /></td><td>Evolution of group</td><td>20</td>
</tr>
</table>
<br/>
<button id='btn_iss'>Issue</button>
<br/>
<table>
<tr>
<th>Select</th><th>Name</th><th>Issued Qnt</th>
</tr>
<tr>
<td><input type='checkbox' value='1' name='std' /></td><td>Rahul</td><td><input type='text' value='' class='qnt'></td>
</tr>
<tr>
<td><input type='checkbox' value='2' name='std' /></td><td>Preeti</td><td><input type='text' value='' class='qnt'></td>
</tr>
<tr>
<td><input type='checkbox' value='3' name='std' /></td><td>Prince</td><td><input type='text' value='' class='qnt'></td>
</tr>
</table>
</body>
</html>
value will always be a string, the best way to check if the string is convertible to a number is window.isNaN function (NOT to be confused with Number.isNaN):
if(window.isNaN(value)) {
/* act accordingly, the value is not a number */
}
If you wish to convert that value string into a number just use the Number constructor
value = Number(value)
As stated by #Jaromanda X an inputs value is always a string so you need to convert it to an integer with parseInt and use isNaN() to check if parseInt(value) is not a number:
if(isNaN(parseInt(value))){
var std_qnt = 0;
alert('Please type number only');
return false;
}
window.onload=function(){
bk_issue();
}
function bk_issue(){
document.getElementById('btn_iss').onclick=function(){
if(document.querySelectorAll('input[name="book"]:checked').length===0){
alert('Please check at least one book');
return false;
}
if(document.querySelectorAll('input[name="std"]:checked').length===0){
alert('Please check at least one student or staff');
return false;
}
else{
var ttl_qnt = document.querySelector('input[name="book"]:checked').getAttribute('data-id');
var std = document.querySelectorAll('input[name="std"]:checked');
var iss_qnt=0;
for (var i=0;i<std.length;i++){
var value = std[i].closest('tr').getElementsByTagName('td')[2].querySelector('.qnt').value;
if(value===''){
var std_qnt = 0;
alert('Please fill book quantity in checked student field');
return false;
}
if(isNaN(parseInt(value))){
var std_qnt = 0;
alert('Please type number only');
return false;
}
else{
var std_qnt = std[i].closest('tr').getElementsByTagName('td')[2].querySelector('.qnt').value;
}
iss_qnt += parseInt(std_qnt);
}
alert(iss_qnt);
}
}
}
<html>
<head>
</head>
<body>
<table>
<tr>
<th>Select</th><th>Book</th><th>Qnt</th>
</tr>
<tr>
<td><input type='radio' name='book' value='1' data-id='20' /></td><td>Social Experiment</td><td>20</td>
</tr>
<tr>
<td><input type='radio' name='book' value='1' data-id='12' /></td><td>Evolution of group</td><td>20</td>
</tr>
</table>
<br/>
<button id='btn_iss'>Issue</button>
<br/>
<table>
<tr>
<th>Select</th><th>Name</th><th>Issued Qnt</th>
</tr>
<tr>
<td><input type='checkbox' value='1' name='std' /></td><td>Rahul</td><td><input type='text' value='' class='qnt'></td>
</tr>
<tr>
<td><input type='checkbox' value='2' name='std' /></td><td>Preeti</td><td><input type='text' value='' class='qnt'></td>
</tr>
<tr>
<td><input type='checkbox' value='3' name='std' /></td><td>Prince</td><td><input type='text' value='' class='qnt'></td>
</tr>
</table>
</body>
</html>
I Cannot get the javascript to work! I need the Password and Re-Type Password fields, validate that both have values and that the user has entered the same password in both fields (i.e. password match) validate the password field must be more than 8 characters.I dont want to use the alert function instead, highlight the uncompleted fields with red background and a text message next to each uncompleted field (in red color) with the error message.
I have spent 3 days doing this!! any help appreciated.`
function validate() {
var fn =
document.getElementById("FName");
if (fn.value == "") {
{
document.getElementById("FName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var sn =
document.getElementById("SName");
if (sn.value == "") {
document.getElementById("SName").style.borderColor = "red";
return false;
}
return true;
}
function validate() {
var un =
document.getElementById("UName");
if (un.value == "") {
document.getElementById("UName").style.borderColor = "red";
return false;
}
return true;
}
function checkPass() {
var pass = document.getElementById('pass');
var c_pass = document.getElementById(' c_pass')
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value == c_pass.value) {
c_pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
} else {
c_pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
}
return true;
}
}
<body>
<form action="Linkpage.html" id="myForm" method="post" name="myForm" onsubmit="return(validate())">
</form>
<br>
<table>
<tr>
<td align="center" colspan="2"><span style="font-size:50px; color:blue;">Registration form</span>
</td>
</tr>
<tr>
<td align="center" colspan="2">Welcome to our website
<br>please fill in <span style=" color:red;">all</span>
<b><ins>fields</ins></b>
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input autofocus="" id="FName" placeholder="Enter First name " type="text">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input id="SName" placeholder="Enter Last name " type="text">
</td>
</tr>
<tr>
<td>Username</td>
<td>
<input id="UName" placeholder="Enter username " type "text">
</td>
</tr>
<tr>
<td>Age</td>
<td>
<input id="Age" placeholder="Enter age" type="text">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input id="pass" placeholder="Enter password " type="password">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input name="confirm password" id="c_pass" placeholder="Re-type your password " type="password" onkeyup="checkPass(); return false;">
<span id="confirmMessage" class="confirmMessage"></span>
</td>
</tr>
<tr>
<td rowspan="2">Gender</td>
<td>
<input name="mGender" type="radio" value="Male">Male</td>
</tr>
<tr>
<td>
<input name="fGender" type="radio" value="Female">Female</td>
</tr>
<tr>
<td>Available</td>
<td>
<input id="checkbox" type="checkbox">
</td>
</tr>
<tr>
<td>Course</td>
<td>
<select>
<option value="Mobile App">
Mobile App
</option>
<option value="Cloud">
Cloud
</option>
<option value="Software Development">
Software Development
</option>
</select>
</td>
</tr>
<tr>
<td class="Comments">Comments</td>
<td>
<br>
<textarea cols="30" name="Comments" placeholder="Type your comments here." rows="6"></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="4" align="center">
<input name="submit" onclick="return validate()" type="submit" value="Register" align="center" />
</td>
</tr>
</table>
</body>
A couple of things here...
Get rid of the table, tr and td. You open a form and then you close it. Add all of your input fields in the form.
Then don't add three functions all called validate. Which one do you suppose is going to be called?
Rather change them to
function validateFname()
function validateSname()
function validateUname()
then
Use === and !=== instead of == and !=.
I think when you start clearing up your JavaScript and your HTML, things will start to make more sense.
Did you try to debug your code using Chrome's debugger or similar?
Each time you write the validate() function, you're overwriting the previous instance of it.
I recommend instead of using the same function name 3 times, write 2 different functions - matches() and required(), each with a different purpose.
matches(field1, field2){
return field1 == field2;
}
required(field){
return field != false;
}
Then you can pass into those functions the various fields you're validating.
There are a lot of bugs in your code and this is normal as a beginner its great to see you trying. So what I have done is took a look at your javascript. I am not going to re-write you whole script but I have commented out the part you should take a look at and try and comment one part at a time to see where you problem is. But I did get your match password working for you by commenting out your other stuff. Just try this for now. Then remove comments line by line until it stops working again. This will tell you how to find the other error's in your script.
<script>
function checkPass(){
var passValue = document.getElementById('pass').value;
var c_passValue = document.getElementById('c_pass').value;
var c_passID = document.getElementById('c_pass');
var message = document.getElementById('confirmMessage');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(passValue == c_passValue) {
c_passID.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!";
} else {
c_passID.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!";
}
}
</script>
Okay so the issue was that you were attempting to change the color of the value of the c_pass and not the id itself. I renamed your variables to help you understand why it was breaking. Again this is only for the checkPass function. If you comment out all the other stuff and just use this script for now this will help you isolate the checkPass function and see that it works. I hope this helps.
i want to show the error messages next to the input element and if there's no error messages then send the data to the server (clear data from form) so fire the function on submit
http://codepen.io/anon/pen/RPNpNw
the problem is the error messages showed and disappeared quickly (blink)
but when change the input type to button
http://codepen.io/anon/pen/EjaZqe
will work but the data will be still in form and not cleared as input type="submit" will do
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<form>
<table style="width:50%;">
<tr>
<td>first name</td>
<td><input type="text" id="txtfname" /></td>
<td><span id="error"></span></td>
</tr>
<tr>
<td>age</td>
<td><input type="number" id="txtage" onblur="checkAge(txtage)" /></td>
<td><span id="errorage"></span></td>
</tr>
<tr>
<td>user name</td>
<td><input type="text" id="txtuser" /></td>
<td><span id="erroruser"></span></td>
</tr>
<tr>
<td>country</td>
<td>
<select onselect="checkSelect(this)" id="slct">
<option selected="selected" value="default">select your country</option>
<option>egypt</option>
<option>usa</option>
</select>
</td>
<td><span id="errorslct"></span></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
</table>
</form>
<script>
function allvalidate() {
validate();
checkAge(txtage);
checkuser(txtuser);
checkSelect(this);
}
function validate() {
var txtf = document.getElementById('txtfname');
if (txtf.value == 0 || txtf.value == null) {
document.getElementById('error').innerText = ('you must enter firstname');
document.getElementById('error').style.color = 'red';
txtf.focus();
return false;
}
else {
document.getElementById('error').innerText = ('');
//return true;
}
}
function checkAge(input) {
if (input.value < 18 || input.value > 70) {
document.getElementById('errorage').innerText = ('age must be from 18 :70');
document.getElementById('errorage').style.color = 'red';
return false;
}
else {
document.getElementById('errorage').innerText = ('');
return true;
}
}
function checkuser(input) {
var pattern = '^[a-zA-Z]+$';
if (input.value.match(pattern)) {
document.getElementById('erroruser').innerText = '';
return true;
}
else {
document.getElementById('erroruser').innerText = ('enter valid email');
document.getElementById('erroruser').style.color = 'red';
return false;
}
}
function checkSelect() {
var select=document.getElementById('slct')
if (select.value=='default') {
document.getElementById('errorslct').innerText = ('you must choose country');
document.getElementById('errorslct').style.color = 'red';
return false;
}
else {
document.getElementById('errorslct').innerText = '';
return true;
}
}
</script>
</body>
</html>
Change
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
To:
<td><input type="submit" value="register" onclick="return allvalidate()" /></td>
Otherwise the boolean value is discarded. You also need to change allvalidate to actually return false if one of the validations fail:
function allvalidate() {
var validated = true;
if (!validate()) validated = false;
if (!checkAge(txtage)) validated = false;
if (!checkuser(txtuser)) validated = false;
if (!checkSelect(this)) validated = false;
return validated;
}
<tr>
<td></td>
<td><input type="submit" value="register" onclick="allvalidate()" /></td>
</tr>
well, I'm not expert but what I think is that data is not sending, you need to call the function on onsubmit event, instead of calling it on onclick event. It would send the data as well.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have been working on this code for my GCSE assessment but I can't seem to get the JavaScript to work , I have looked through my code for a couple of weeks now and I still can't find the logic error within it I suspect that I have missed something out to get the Java to work , if anyone can help it would be extremely helpful
my current code I am looking through:
<head>
<title>Exam entry</title>
<script> language="javascript" type="text/javascript".
function ValidateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElemenById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.geElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.exam number.value=="") {
msg+="You must enter your exam number \n";
document.ExamEntry.subject.focus();
document.geElementById('exam number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="exam number">Exam Number</td>
<td><input type="text" name="Exam Number" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit" onclick="return
validateForm();"/></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
Tidying up your snippet presents the real issue:
function ValidateForm() {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElemenById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.geElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.exam number.value=="") {
msg+="You must enter your exam number \n";
document.ExamEntry.subject.focus();
document.geElementById('exam number').style.color="red";
result = false;
}
if(msg==""){
return result;
}
{
alert(msg)
return result;
}
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html">
<table width="50%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<tr>
<td id="exam number">Exam Number</td>
<td><input type="text" name="Exam Number" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit" onclick="return
validateForm();"/></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
SyntaxError: missing ) after condition
if (document.ExamEntry.exam number.value=="") {
---------------------------^
if your variable has a space in it, you cant use the dot notation, but you can use the square bracket notation. Change that line to:
if (document.ExamEntry["Exam Number"].value=="") {
I am very new to really writing javascript (borrowing and editing, not so new). So with a little help from google and code guru and adobe cookbook, I have come up with this simple form to be embedded into an iPad publication (this is just my test, not the final product). I have gotten it this far with no errors if the debug console and it seems to pass W3C compliance, but it also doesn't do anything! It doesn't generate the answers??? I am hoping someone can help me out or steer me in the right direction. the code for the page is below: Thanks in advance...
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.innerHTML = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.innerHTML = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.innerHTML = + (TotalsCost1 - TotalsCost2);
}
};
</script>
</body>
btn.onclick = (function(){...})();
You need to put onclick events inside self-calling code, or what are called closures. Move your entire btn.onclick function inside of this bit of code: (...)() in order to make it work.
Good attempt, a few small things wrong but pretty close!
I have made a few changes here.
As mentioned in a comment, I wrapped the function with brackets (function() {...});
I also changed innerHTML to be value as we are updating text inputs, and your savings calculation should be input.value, which I have updated for you.
Let me know how you get on!
<body>
<form id="form1" name="form1" method="post" action="">
<table width="500" border="1">
<tr>
<th scope="col">Item</th>
<th scope="col">Cost 1</th>
<th scope="col">Cost 2</th>
</tr>
<tr>
<th scope="row">Manikin</th>
<td><input type="text" name="ManikinCost1" id="ManikinCost1" tabindex="1" /></td>
<td><input type="text" name="ManikinCost2" id="ManikinCost2" tabindex="2" /></td>
</tr>
<tr>
<th scope="row">Instructor</th>
<td><input type="text" name="InstructorCost1" id="InstructorCost1" tabindex="3" /></td>
<td><input type="text" name="InstructorCost2" id="InstructorCost2" tabindex="4" /></td>
</tr>
<tr>
<th scope="row">Books</th>
<td><input type="text" name="BooksCost1" id="BooksCost1" tabindex="5" /></td>
<td><input type="text" name="BooksCost2" id="BooksCost2" tabindex="6" /></td>
</tr>
<tr>
<th scope="row">Totals</th>
<td><input type="text" name="TotalsCost1" id="TotalsCost1" tabindex="7" /><span id="TotalsCost1"></span></td>
<td><input type="text" name="TotalsCost2" id="TotalsCost2" tabindex="8" /><span id="TotalsCost2"></span></td>
</tr>
<tr>
<th scope="row">Savings</th>
<td colspan="2"><input type="text" name="Savings" id="Savings" /><span id="Savings"></span></td>
</tr>
</table>
<p>
<input type="button" name="calculate" id="calculate" value="Calculate" />
</p>
<p> </p>
<p> </p>
</form>
<script type="text/javascript">
var btn = document.getElementById('calculate');
btn.onclick = (function() {
//get the input values
var ManikinCost1 = parseInt(document.getElementById('ManikinCost1').value);
var ManikinCost2 = parseInt(document.getElementById('ManikinCost2').value);
var InstructorCost1 = parseInt(document.getElementById('InstructorCost1').value);
var InstructorCost2 = parseInt(document.getElementById('InstructorCost2').value);
var BooksCost1 = parseInt(document.getElementById('BooksCost1').value);
var BooksCost2 = parseInt(document.getElementById('BooksCost2').value);
// get the elements to hold the results
var TotalsCost1 = document.getElementById('TotalsCost1');
var TotalsCost2 = document.getElementById('TotalsCost2');
var Savings = document.getElementById('Savings');
// create an empty array to hold error messages
var msg = [];
// check each input value, and add an error message to the array if it's not a number
if (isNaN(ManikinCost2)) {
msg.push('Manikin Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost1)) {
msg.push('Instructor Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(InstructorCost2)) {
msg.push('Instructor Cost 2 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost1)) {
msg.push('Book Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(ManikinCost1)) {
msg.push('Manikin Cost 1 is not a number');
// the value isn't a number
}
if (isNaN(BooksCost2)) {
msg.push('Book Cost 2 is not a number');
// the value isn't a number
}
// if the array contains any values, display an error message
if (msg.length > 0) {
TotalsCost1.innerHTML = msg.join(', ');
} else {
TotalsCost1.value = + (ManikinCost1 + InstructorCost1 + BooksCost1);
TotalsCost2.value = + (ManikinCost2 + InstructorCost2 + BooksCost2);
Savings.value = + (TotalsCost1.value - TotalsCost2.value);
}
});
</script>
</body>