Trouble computing - Javascript form - javascript

I'm very new to Javascript and this website, but I'm looking for help on a project of mine.
It's a little rough so far and not complete, but I can't move on until I figure out how to actually get the computations to show up. If I could get help figuring out why the first apple total isn't computing, that would be great!
Here's my full (work in progress) html page:
<html>
<head>
<title>Order Form</title>
<style>
.inBox { width:60px; text-align:right; border: 1px solid green; }
.thWide { width:80px; text-align:right; }
</style>
<script type="text/javascript">
function compute()
{
// Pointers to red asterisks
var spnA = document.getElementById("spnA");
var spnP = document.getElementById("spnP");
var spnG = document.getElementById("spnG");
// Assume no errors yet
var message = "";
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
var apple = form1.txtA.value;
if (apple == "")
apple = 1;
else
apple = parseFloat(apple);
if ( isNaN(apple) )
{
spnA.style.display = "inline";
message = message + "Apple is bad\n";
form1.txtA.select();
}
var pear = form1.txtP.value;
if (pear == "")
pear = 1;
else
pear = parseFloat(pear);
if ( isNaN(pear) )
{
spnP.style.display = "inline";
message = message + "Pear is bad\n";
form1.txtP.select();
}
var grape = form1.txtG.value;
if (grape == "")
grape = 1;
else
grape = parseFloat(grape);
if ( isNaN(grape) )
{
spnG.style.display = "inline";
message = message + "Grape is bad\n";
form1.txtG.select();
}
if ( message != "" )
{
// Show error and clear subA
alert(message);
form1.txtsubA.value = "";
}
else
{
// Compute subA
var subA = length * 5.49;
form1.txtsubA.value = subA;
form1.txtA.select();
}
}
</script>
</head>
<body>
<form id="form1">
<table border="2">
<tr><th colspan="4">Volume Box</th></tr>
<tr><th>Quantity</th><th>Item</th><th>Unit Prics</th><th>Totals</th></tr>
<tr>
<th class="thWide">
<span id="spnA" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtA" class="inBox" tabindex="1" autofocus />
</th><td>Apples</td><td>$5.49</td>
<th style="width:80px;"><input type="text" id="txtsubA" class="inBox" readonly /></th>
</tr><tr>
<th class="thWide">
<span id="spnP" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtP" class="inBox" tabindex="1" autofocus />
</th><td>Pears</td><td>$6.49</td>
<th style="width:80px;"><input type="text" id="txtsubP" class="inBox" readonly /></th>
</tr><tr>
<th class="thWide">
<span id="spnG" style="color:red; font-weight:bold; display:none;">*</span>
<input type="text" id="txtG" class="inBox" tabindex="1" autofocus />
</th><td>Grapes</td><td>$7.49</td>
<th style="width:80px;"><input type="text" id="txtsubG" class="inBox" readonly /></th>
</tr>
<tr><th colspan="4">
<input type="button" value="Compute" onclick="compute();" tabindex="4" />
</th></tr>
</table>
</form>
</body>
</html>

The console in your browser can be very helpful in diagnosing any problems. For example, your code gives this error in the console:
test.html:18 Uncaught ReferenceError: spnL is not defined
I assume you meant for this part:
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
to be:
spnA.style.display = "none";
spnP.style.display = "none";
spnG.style.display = "none";
As for your problem, the issue is in this part:
// Compute subA
var subA = length * 5.49;
Length isn't defined anywhere, you probably mean:
// Compute subA
var subA = apple * 5.49;
And then you will also probably want to change the line after that from
form1.txtsubA.value = subA;
to
form1.txtsubA.value = subA.toFixed(2);
which will only show 2 decimal places.

Get rid of (or comment out):
spnL.style.display = "none";
spnW.style.display = "none";
spnH.style.display = "none";
Collect the values provided in the form (add ".value"):
// Pointers to red asterisks
var spnA = document.getElementById("txtA").value;
var spnP = document.getElementById("txtP").value;
var spnG = document.getElementById("txtG").value;
Swap length for declared values:
// Compute subA
var subA = spnA * 5.49;
And enjoy!

Related

Trying to create a very simple quiz using html, js, and forms

I need it to display green if question 1 is "1", or question 2 is "4". Red otherwise when mark quiz is called. Where am I going wrong with this code? js is located in an external file.
Html:
<body>
<table>
<tr>
<th>Questions</th>
<th>Answer</th>
</tr>
<tr>
<td id="1">
Water is
<ol>
<li> Wet</li>
<li> Ordinary</li>
<li>Purify </li>
<li> Water</li>
</ol>
</td>
<td>
<form name="question1" action="www.quizMarker.ca">
<input type="text" name="quest1" placeholder="Enter Answer">
</form>
</td>
</tr>
<tr>
<td id="2">
Fire is
<ol>
<li> Wet</li>
<li> Ordinary</li>
<li>Purify </li>
<li> Hot</li>
</ol>
</td>
<td>
<form name="question2" ction="www.quizMarker.ca">
<input type="text" name="quest1" placeholder="Enter Answer">
</form>
</td>
</tr>
</table>
<button type="button" onclick="markQuiz()">Mark Quiz</button>
js:
function markQuiz()
{
var q1 = document.forms['question1'];
var q1Ans = q1.elements['quest1'].value;
var q2 = document.forms['question2'];
var q2Ans = q2.elements['quest2'].value;
var row1 = document.getElementById("1");
var row2 = document.getElementById("2");
if(q1Ans = "1")
{
row1.style.backgroundColor = "green";
}
else()
{
row1.style.backgroundColor = "red";
}
if(q2Ans = "4")
{
row2.style.backgroundColor = "green";
}
else()
{
row2.style.backgroundColor = "red";
}
}
Right now markQuiz is not doing anything when called. Also if there is a simpler way to accomplish this task, suggestions would be helpful.
you may need "==" or "===" instead of "=", which mean assign.
if(a = "1") {
//code here always execute
}
if(a === "1") {
//code here only execute when a is String with value "1"
}
there is an extra = symbol in your code
if(q1Ans = "1")
{
row1.style.backgroundColor = "green";
}
correct syntax is:
if(q1Ans == "1")
{
row1.style.backgroundColor = "green";
}
Please check the changes i made
function markQuiz()
{
var q1Ans = document.forms['question1'].quest1.value;
var q1Ans = document.forms['question2'].quest2.value;
// PLease change the ids of the td ttag
var row1 = document.getElementById("table1");
var row2 = document.getElementById("table2");
if(q1Ans === "1")
{
row1.style.backgroundColor = "green";
}
else
{
row1.style.backgroundColor = "red";
}
if(q2Ans === "4")
{
row2.style.backgroundColor = "green";
}
else
{
row2.style.backgroundColor = "red";
}
}

form display results on same page + random answer

So I have a 3 question "what profession are you quiz"... and after the text, radio and select are chosen and submitted, the results are to show next to them. The text and select do but not the radio. The select shows if I have the radios as, if ((php.checked==false) && (asp.checked==false) && (js.checked==false)){rad.setAttribute("style", "display:inline");} ... How my set up is now the text shows but the radio and select dont. Also I need to have an array that holds the solutions and once the answers get submitted, it randomly shows a solution, like "You are a Warrior!". And this is a .PHP extension. Heres my code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Ex 2</title>
<link href="styles.css" rel="stylesheet">
<script>
function checkForm(){
var chk = true;
var mName = document.getElementById("txtMeth");
var meth = document.getElementById("methMess");
var rad = document.getElementById("radMess");
var sel = document.getElementById("selMess");
var php = document.getElementById("a");
var asp = document.getElementById("b");
var js = document.getElementById("c");
var arr = document.getElementById("imp");
mName.style.backgroundColor="#fff";
meth.setAttribute("style", "display:none");
rad.setAttribute("style", "display:none");
sel.setAttribute("style", "display:none");
if (mName.value=='no'){
document.getElementById("methMess").innerHTML = "No";
meth.setAttribute("style", "display:inline");
chk = false;
}
if (mName.value=='yes'){
document.getElementById("methMess").innerHTML = "Yes";
meth.setAttribute("style", "display:inline");
chk = false;
}
if (php.value==A){
document.getElementById("radMess").innerHTML = "Healer";
rad.setAttribute("style", "display:inline");
chk = false;
}
if (asp.value==B){
document.getElementById("radMess").innerHTML = "Dark";
rad.setAttribute("style", "display:inline");
chk = false;
}
if (js.value==C){
document.getElementById("radMess").innerHTML = "One with the Elements";
rad.setAttribute("style", "display:inline");
chk = false;
}
if (arr.value==1){
document.getElementById("selMess").innerHTML = "Rifle";
sel.setAttribute("style", "display:inline");
chk = false;
}
if (arr.value==2){
document.getElementById("selMess").innerHTML = "Bown and Arrow";
sel.setAttribute("style", "display:inline");
chk = false;
}
if (arr.value==3){
document.getElementById("selMess").innerHTML = "Daggers";
sel.setAttribute("style", "display:inline");
chk = false;
}
}
</script>
</head>
<body>
<div class="page">
<main role="main">
<article>
<div id="errMess" class="errMess">*Required Fields Missing</div>
<h1>What Guild Wars 2 Profession Are You</h1>
<div class="cssTable" style="margin-top:-25px;">
<form method="post">
<table>
<tr><td colspan="3"></td></tr>
<tr>
<td><div align="right">Do you like to do high damage?</div></td><td width="217">
<input id="txtMeth" name="txtMeth" type="text" size="25"></td><td ><div id="methMess" style="display:none"></div></td></tr>
<tr>
<td><div align="right">What best describes you?</div></td><td>
<input id="a" type="radio" name = "group1" value="A">Healer</input>
<input id="b" type="radio" name = "group1" value="B">Dark</input>
<input id="c" type="radio" name = "group1" value="C">Earthling</input>
</td><td><div id="radMess" style="display:none"></div></td>
</tr>
<tr>
<td>What weapon would you like to have?</td>
<td>
<select id="imp"><option value="0" selected="true">Select One</option>
<option value="1">Rifle</option>
<option value="2">Bow and Arrow</option>
<option value="3">Daggers</option></select>
</td><td><div id="selMess" style="display:none"></div></td>
</tr>
<tr><td colspan="3" align="right"><input type="button" class="styled-button-7" value="Send" onclick="checkForm()"/></td></tr></table></form></div></article>
</main></div>
</body>
</html>
It is like this that your radio buttons will always have the values 'A', 'B' or 'C', it is simply how you define them in your HTML.
A radiobutton should be checked for active by using the '.checked' property rather than over a value.
Please see the js fiddle here
and the changes i made to your code are:
I updated your if's
if (php.checked) {
document.getElementById("radMess").innerHTML = "Healer";
rad.setAttribute("style", "display:inline");
chk = false;
}
if (asp.checked) {
document.getElementById("radMess").innerHTML = "Dark";
rad.setAttribute("style", "display:inline");
chk = false;
}
if (js.checked) {
document.getElementById("radMess").innerHTML = "One with the Elements";
rad.setAttribute("style", "display:inline");
chk = false;
}
So... I had to rename everything because I kept getting confused. Do not just turn this in or copy it exactly... your teacher will probably know you didn't do it.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Ex 2</title>
<link href="styles.css" rel="stylesheet">
<style>td { height:25px }</style>
<script>
function checkForm() {
var high = document.getElementById('high'); // mName
var desc = document.getElementsByName('desc'); // group1
var weapon = document.getElementById('weapon'); // imp
// console.log(high);
// console.log(desc);
// console.log(weapon);
// get the checked radio button value to be used later
var desc_value;
for(var i=0; i<desc.length; i++){
if (desc[i].checked) desc_value = desc[i].value;
}
var error = false;
if (!high.value) {
// if you need to do validation for Yes/No, do it here
document.getElementById('errMess').innerHTML = 'high damage missing';
error = true;
}
else if (!desc_value) {
document.getElementById('errMess').innerHTML = 'desc missing';
error = true;
}
else if (!weapon.value) {
document.getElementById('errMess').innerHTML = 'weapon missing';
error = true;
}
if (!error) {
document.getElementById('errMess').innerHTML = '';
// do you like to do high damage?
high.style.background = '#fff';
high.style.display = 'none';
var highMess = document.getElementById('highMess');
highMess.innerHTML = high.value;
highMess.setAttribute('style', 'display:inline');
// what best describes you?
var desc_val;
var desc_msg = document.getElementById('descMsg');
desc_msg.setAttribute('style', 'display:inline');
desc_msg.innerHTML = desc_value;
for(var i=0; i<desc.length; i++){
// loop through the radio button group to hide the parent <span>
desc[i].parentNode.setAttribute('style', 'display:none');
}
// what weapon would you like to have?
weapon.style.display = 'none';
var weapon_val = weapon.options[weapon.selectedIndex].value;
var weapon_msg = document.getElementById('weaponMsg');
weapon_msg.innerHTML = weapon_val;
weapon_msg.setAttribute('style', 'display:inline');
}
}
</script>
</head>
<!-- this sets the selected option to being out of range (aka blank/empty) -->
<body onload="document.getElementById('weapon').selectedIndex = -1;">
<div class="page">
<main role='main'>
<article>
<div id='errMess' class='errMess' style='font-weight:bold; height:26px'></div>
<h1>What Guild Wars 2 profession are you.....?</h1>
<div class='cssTable' style='margin-top:-25px;'>
<form method='post'>
<table>
<tr><td colspan='3'></td></tr>
<tr>
<td><div align='right'>Do you like to do high damage?</div></td>
<td width='217px'><input id='high' name='high' type='text' size='25'/></td>
<td><div id='highMess' style='display:none'></div></td>
</tr>
<tr>
<td><div align='right'>What best describes you?</div></td>
<td>
<!-- i added spans outside of the <input/> so you could hide the text easily, too -->
<span><input id='healer' type='radio' name='desc' value='healer'>Healer</input></span>
<span><input id='dark' type='radio' name='desc' value='dark'>Dark</input></span>
<span><input id='earthling' type='radio' name='desc' value='earthling'>Earthling</input></span>
</td>
<td><div id='descMsg' style='display:none'></div></td>
</tr>
<tr>
<td>What weapon would you like to have?</td>
<td>
<select id='weapon' name='weapon'>
<option value='rifle'>Rifle</option>
<option value='bow_arrow'>Bow and Arrow</option>
<option value='daggers'>Daggers</option>
</select>
</td>
<td><div id='weaponMsg' style='display:none'></div></td>
</tr>
<tr>
<td colspan='3' align='right'><input type='button' class='styled-button-7' onClick='checkForm()' value='Submit'/></td>
</tr>
</table>
</form>
</div>
</div>
</article>
</main>
</body>
</html>

How to Display Commas After Every Third Number Without Compromising Calculator

I am trying to create a loan calculator that uses commas to separate every third number. For example, $1,000,000.75.
Is there a way to display all of the input values like this, without compromising the actual calculation of numbers?
Right now, if a comma is entered in any of the inputs, than the calculated input (input that displays the calculation), throws an error (NaN). I am wondering if there is any way to do this using something such as PHP or JavaScript?
Here is a picture of a working example of my loan calculator:
Here is my full page code for the loan calculator:
<!doctype html>
<html>
<head>
<style>
body {
font-family:arial,verdana,sans-serif;
}
img a {
border:none;
}
img {
border:none;
}
.bback {
text-align:center;
width:100%;
}
#image {
width:84px;
height:41px;
}
#stretchtable {
width:60%;
max-width:500px;
min-width:200px;
}
.fontwhite {
color:white;
background-color:black;
border:4px grey solid;
padding:5px;
text-align:left;
}
</style>
<meta charset="utf-8">
<title> ::: Loan Calculator</title>
</head>
<body bgcolor="#102540">
<script language="JavaScript">
<!--
function showpay() {
if ((document.calc.loan.value == null || document.calc.loan.value.length == 0) ||
(document.calc.months.value == null || document.calc.months.value.length == 0)
||
(document.calc.rate.value == null || document.calc.rate.value.length == 0))
{ document.calc.pay.value = "Incomplete data";
}
else
{
var princ = document.calc.loan.value;
princ = princ.replace(',','');
var myfloat = parseFloat(princ);
var term = document.calc.months.value;
term = term.replace(',','');
var myfloat1 = parseFloat(term);
var intr = document.calc.rate.value / 1200;
intr = intr.replace(',','');
var myfloat2 = parseFloat(intr);
document.calc.pay.value = (myfloat * myfloat2 / (1 - (Math.pow(1/(1 + myfloat2), myfloat1)))).toFixed(2)
}
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
// -->
</script>
<script>
function trimDP(x, dp) {
x = parseFloat(x);
if (dp === 0)
return Math.floor(x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((x) * dp) / dp).toString();
}
window.addEventListener('load', function () {
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
});
</script>
<div class="bback">
<h1 style="color:white;font-size:16px;">G.B.M. Trailer Service Ltd. Loan Calculator</h1>
<a href="index.html">
<img src="images/backbutton.png" alt="Back Button" id="image" title="Back"></a><br /><br />
<center>
<div class="fontwhite" style="width:60%;">
The results of this loan payment calculator are for comparison purposes only.
They will be a close approximation of actual loan
repayments if available at the terms entered, from a financial institution. This
is being
provided for you to plan your next loan application. To use, enter values
for the
Loan Amount, Number of Months for Loan, and the Interest Rate (e.g.
7.25), and
click the Calculate button. Clicking the Reset button will clear entered
values.
</div>
</center>
</div>
<p>
<center>
<form name=calc method=POST>
<div style="color:white; font-weight:bold; border:4px grey outset; padding:0px; margin:0px;" id="stretchtable">
<table width="100%" border="1" style="border:1px outset grey">
<tr><th bgcolor="black" width=50%><font color=white>Description</font></th>
<th bgcolor="black" width=50%><font color=white>Data Entry</font></th></tr>
<tr><td bgcolor="black">Loan Amount</td><td bgcolor="black" align=center><input
type=text name=loan
size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Loan Length in Months</td><td bgcolor="black"
align=center><input type=text
name=months size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Interest Rate</td><td bgcolor="black" align=center><input
type=text name=rate
size=10 onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black">Monthly Payment</td><td bgcolor="black"
align=center><em>Calculated</em> <input
type=text name=pay size=10 class="dp2" onkeyup="format(this)"></td></tr>
<tr><td bgcolor="black"align=center><input type=button onClick='showpay()'
value=Calculate></td><td bgcolor="black" align=center><input type=reset
value=Reset></td></tr>
</table>
</div>
</form>
<div style="width:60%;">
<font size=2 color=white>Enter only numeric values (no commas), using decimal points
where needed.<br>
Non-numeric values will cause errors.</font>
</center>
</div>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>
</body>
</html>
I am looking for a solution to my problem, as I am not experienced with this type of code. Suggestions may only get me so far.
Thank you for any help. All help is greatly appreciated.
Replace this:
var intr = document.calc.rate.value / 1200;
with this
var intr = (parseFloat(document.calc.rate.value) / 1200).toString()
For the adding commas bit, replace this:
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2)
with this
document.calc.pay.value = (princ * intr / (1 - (Math.pow(1/(1 + intr), term)))).toFixed(2).toLocaleString()
there are other ways to do it, but this seems like the fastest way without introducing more functions. JavaScript gives us toLocaleString which should be your most flexible option.
Before calculation simply use .replace(',','') to remove the commas. Then you need to cast it to to a float by using parseFloat(). Then when you go to display the numbers you can reformat it with commas if you would like.
var mystring = '10,000.12';
mystring = mystring.replace(',','');
var myfloat = parseFloat(mystring);
For adding the commas back in you can do something like this:
How to print a number with commas as thousands separators in JavaScript
From that answer:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}

How to perform validation for Captcha using JavaScript?

I am new to UI design. I have created Captcha, Please anyone give me an idea to validate Captcha using JavaScript.Thanks in advance. I have added my code below.
Code for getting new Captcha:
<html>
<head>
<script language="javascript" type="text/javascript">
function getCaptcha() {
var chars = "0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9Jj0Kk1Ll2Mm3Nn4Oo5Pp6Qq7Rr8Ss9Tt0Uu1Vv2Ww3Xx4Yy5Zz";
var string_length = 5;
var captchastring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
captchastring += chars.substring(rnum,rnum+1);
}
document.getElementById("randomfield").innerHTML = captchastring;
}
</script>
<style>
HTML Code:
</head>
<body onload="getCaptcha();">
<form name="randform">
<table style="border:1px solid #ecece4">
<tr><td colspan="2" align="center"><strong>Contact Us Form</strong></td></tr>
<tr><td>Enter Captcha Code</td><td><input type="text" id="txtcode"/></td></tr>
<tr>
<td>
</td>
<td>
<div id="captcha">
<div id="captcha_gen">
<label align="center" id="randomfield"></label>
</div>
</div><input type="button" value="Refresh" onClick="getCaptcha();"/></td></tr>
<tr><td colspan="2" align="center"><input type="button" value="Submit"/></td></tr>
</table>
</form>
</body>
<html>
function validateCaptcha()
{
var chr = document.getElementById("tbxCaptcha").value;
var cap = document.getElementById("randomfield").innerHTML;
if (chr==cap)
{
return true;
}
else
{
alert ("Please enter valid verification code");
return false;
}
}

Alert box shows up multiple times on javascript

This is very simple code, and similar to my other question.
When I click submit, the alert box shows up three times for option one, twice for two, and once for three.
Here is the part of the code where the problem is most probably located:
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
And here is my whole code. It all works fine except for this.
<!-- saved from url=(0055)file:///C:/Users/Bartek/Downloads/Exam%20entry4.1.2.htm -->
<html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"></head><body><h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="file:///C:/Users/Bartek/Downloads/success.html">
<input type="radio" name="r1" value="GCSE">GCSE
<input type="radio" name="r1" value="AS">AS
<input type="radio" name="r1" value="A2">A2
<table width="50%" border="0">
<tbody>
<tr>
<td id="name" style="color: black; ">Name</td>
<td>
<input type="text" name="name">
</td>
</tr>
<tr>
<td id="subject" style="color: black; ">Subject</td>
<td>
<input type="text" name="subject">
</td>
</tr>
<tr>
<td id="enumber" style="color: black; ">Examination Number</td>
<td>
<input type="text" name="enumber">
</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>
</tbody></table>
</form>
<script>
function validateForm() {
var result = true;
var msg = "";
if (document.ExamEntry.name.value == "") {
msg += "You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color = "red";
result = false;
}
if (document.ExamEntry.subject.value == "") {
msg += "You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color = "red";
result = false;
}
if (document.ExamEntry.enumber.value.length != 4) {
msg += "The examination number must be exactly four characters long \n";
document.ExamEntry.enumber.focus();
document.getElementById('enumber').style.color = "red";
result = false;
}
var chosen = ""
var len = document.ExamEntry.r1.length
for (var i = 0; i < len; i++) {
if (document.ExamEntry.r1[i].checked) {
chosen = document.ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
if (msg == "") {
return result;
} {
alert(msg);
return result;
}
}
</script>
</body>
</html>
This is GCSE computing coursework.
for (var i = 0; i <len; i++) {
if (document. ExamEntry.r1[i].checked) {
chosen = document. ExamEntry.r1[i].value
}
if (chosen != "") {
confirm(chosen)
}
}
chosen won't be "" if it was set before; you don't set it back to "" if the item wasn't checked, and so it'll confirm the last one that was. Just merge them.
for(var i = 0; i < document.ExamEntry.r1.length; i++) {
if(document.ExamEntry.r1[i].checked) {
confirm(document.ExamEntry.r1[i].value);
}
}
You were missing an else.
if (!msg) {
return result;
} else {
alert(msg);
return result;
}

Categories