It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
How to save log to .txt ?
<html>
<head>
<title>Javascript Stopwatch</title>
<script language="javascript">
var base = 60;
var clocktimer,dateObj,dh,dm,ds,ms;
var readout='';
var h=1;
var m=1;
var tm=1;
var s=0;
var ts=0;
var ms=0;
var show=true;
var init=0;
var filePath = "/Users/ResetOfDirectoryPath/testWrite.txt";
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
function uncheckedRadio() {
var radio_1 = document.clockform.gName;
var radio_2 = document.clockform.aName;
if(radio_1.length == undefined)
radio_1.checked = false;
else
for(var i = 0; i < radio_1.length; i++)
radio_1[i].checked = false;
if(radio_2.length == undefined)
radio_2.checked = false;
else
for(var i = 0; i < radio_2.length; i++)
radio_2[i].checked = false;
}
unction clearALL() {
clearTimeout(clocktimer);
h=1;m=1;tm=1;s=0;ts=0;ms=0;
init=0;show=true;
readout='00:00:00.00';
document.clockform.clock.value=readout;
document.clockform.m0.value = '';
uncheckedRadio();
nrGola = 1;
}
var nrGola = 1;
function addMEM() {
if (init>0)
{
var mC = document.clockform.m0;
var gol = getCheckedValue(document.clockform.gName);
var asy = getCheckedValue(document.clockform.aName);
if(gol != '')
{
var mesOut = nrGola + " G: " + gol;
if(asy != '')
{
if(asy == gol)
{
alert('Error, asysta taki sam jak strzelca');
uncheckedRadio();
return false;
}
mesOut = mesOut + ", A: " + asy;
}
else
mesOut = mesOut + ", A: brak";
mesOut = mesOut + ", " + readout;
if(mC.value != '')
mC.value = mC.value + "\n" + mesOut;
else
mC.value = mesOut;
nrGola++;
uncheckedRadio();
}
else
alert('Nie wybrano strzelcy');
}
}
function startTIME() {
var cdateObj = new Date();
var t = (cdateObj.getTime() - dateObj.getTime())-(s*1000);
if (t>999) { s++; }
if (s>=(m*base)) {
ts=0;
m++;
} else {
ts=parseInt((ms/100)+s);
if(ts>=base) { ts=ts-((m-1)*base); }
}
if (m>(h*base)) {
tm=1;
h++;
} else {
tm=parseInt((ms/100)+m);
if(tm>=base) { tm=tm-((h-1)*base); }
}
ms = Math.round(t/10);
if (ms>99) {ms=0;}
if (ms==0) {ms='00';}
if (ms>0&&ms<=9) { ms = '0'+ms; }
if (ts>0) { ds = ts; if (ts<10) { ds = '0'+ts; }} else { ds = '00'; }
dm=tm-1;
if (dm>0) { if (dm<10) { dm = '0'+dm; }} else { dm = '00'; }
dh=h-1;
if (dh>0) { if (dh<10) { dh = '0'+dh; }} else { dh = '00'; }
readout = dh + ':' + dm + ':' + ds + '.' + ms;
if (show==true) { document.clockform.clock.value = readout; }
clocktimer = setTimeout("startTIME()",1);
}
function findTIME() {
if (init==0) {
dateObj = new Date();
startTIME();
init=1;
}
}
/*
var times = {};
window.onload=function() {
var inpt = document.getElementsByTagName("input");
for (var i=0,n=inpt.length;i<n;i++) {
if (inpt[i].type=="radio") inpt[i].onclick=function() {
times[this.id]=this.form.m0.value=this.form.clock.value;
}
}
}
*/
function showTimes() {
var temp = document.clockform.m0.value;
if(temp != '')
{
uriContent = "data:text/plain;charset=utf-8," + encodeURIComponent(temp);
newWindow=window.open(uriContent, 'txt');
}
}
</script>
</head>
<body bgcolor=tan>
<form name="clockform">
<table bgcolor=cornsilk align=center cellpadding=5 border=1 bordercolor=burlywood><tr><td>
<table cellpadding=3 cellspacing=0 border=0 align=center>
<tr>
<td bgcolor=wheat><input name=clock value="00:00:00.00" style="text-align:center; width:174px; height:35px; font-size:24; font-weight:bold"></td>
<td valign=top bgcolor=wheat><input name=clearer type=button value="Reset" onclick="clearALL()"></td>
</tr>
<tr>
<td colspan=2 bgcolor=wheat>
<input name=starter type=button value="Start" style="width:97px; font-weight:bold" onclick="findTIME()"> <input name=marker type=button id ="dupa" value="Mark" style="width:84px" onclick="addMEM()"><br><font style="font-size:9pt"> </font></td>
</tr>
<tr><td>
<input type="radio" name="gName" value="1" /> 1<br>
<input type="radio" name="gName" value="2" /> 2<br>
<input type="radio" name="gName" value="3" /> 3<br>
<input type="radio" name="gName" value="4" /> 4<br>
<input type="radio" name="gName" value="5" /> 5<br>
<input type="radio" name="gName" value="6" /> 6<br>
</td>
<td>
<input type="radio" name="aName" value="1" /> 1<br>
<input type="radio" name="aName" value="2" /> 2<br>
<input type="radio" name="aName" value="3" /> 3<br>
<input type="radio" name="aName" value="4" /> 4<br>
<input type="radio" name="aName" value="5" /> 5<br>
<input type="radio" name="aName" value="6" /> 6<br>
</td>
</tr>
<tr><td colspan="2">
<textarea name="m0" style="text-align:left; width:83px cols="40" rows="5" readonly="readonly">
</textarea>
<input type="button" onclick="showTimes()" value="show times">
</td>
</tr>
</table>
</form>
</body>
</html>
JavaScript, running in a browser, under normal security conditions, cannot access the user's file system.
You need to have ajax or something else that can write to the server with the right permissions to write to a log file on the server. The JavaScript itself can not write a log file to the server or the client as it is executed off the server and it does not have access to the clients computer (Image getting viruses through JavaScript if this was true)....Unless you give explicit write access which is very unsafe and very complicated to do.
Related
how to validate all the section by at least choose one option. with my code, it just show the first "please select 1". so how to edit the code to show the all requirement like "pls choose at least one" at beside the section or below the submit button. I'm just a beginner, now learning for JavaScript. You are prefer to done with some code editor, to have a better understand for beginner. Here is my code :
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*454.58;
elec["elec2"] = 200*454.58;
elec["elec3"] = 300*454.58;
elec["elec4"] = 400*454.58;
elec["elec5"] = 500*454.58;
elec["elec6"] = 600*454.58;
elec["elec7"] = 700*454.58;
elec["elec8"] = 800*454.58;
elec["elec9"] = 900*454.58;
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco;
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vpeople()
{
var cp = document.getElementsByName('selectedperson');
for (var i = 0; i < cp.length; i++)
{
if (cp[i].type == 'radio')
{
if (cp[i].checked) {return true}
}
}
return false;
}
function velec()
{
var ce = document.getElementsByName('electricity');
for (var i = 0; i < ce.length; i++)
{
if (ce[i].type == 'radio')
{
if (ce[i].checked) {return true}
}
}
return false;
}
function vrcyalu()
{
var crcyalu = document.getElementsByName('yesalu');
for (var i = 0; i < crcyalu.length; i++)
{
if (crcyalu[i].type == 'checkbox')
{
if (crcyalu[i].checked) {return true}
}
}
return false;
}
function vrcyplas()
{
var crcyplas = document.getElementsByName('yesalu');
for (var i = 0; i < crcyplas.length; i++)
{
if (crcyplas[i].type == 'checkbox')
{
if (crcyplas[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
if(!vpeople())
{
alert("Please select1");
return false;
}
return true;
if(!vwaste())
{
alert("Please select2");
return false;
}
return true;
if(!velec())
{
alert("Please select3");
return false;
}
return true;
if(!vrcyalu())
{
alert("Please select4");
return false;
}
return true;
if(!vrcyplas())
{
alert("Please select5");
return false;
}
return true;
checkAllRecycles;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4 </label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5 </label>
<br/><br/>
<label><i class="fa fa-flash"></i>Energy Consumption Per Month</label>
<br/>
<label> Electricity    </label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0</option>
<option value="elec1">100</option>
<option value="elec2">200</option>
<option value="elec3">300</option>
<option value="elec4">400</option>
<option value="elec5">500</option>
<option value="elec6">600</option>
<option value="elec7">700</option>
<option value="elec8">800</option>
<option value="elec9">900</option>
</select>
<br/><br/>
<label><i class="fa fa-flash"></i>Recycle </label>
<br/>
<label for='yesalu' class="alu"> Aluminium and Steel  </label>
<input type="checkbox" id="yesalu" name='yesalu' onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas"> Plastic                          </label>
<input type="checkbox" id="yesplas" name='yesplas' onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
thx you very much for helping me, stay safe.
hello please check this page :
https://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript
i want to consult issue about javascript jquery
i want this value > 20 && < 40 clear or reset option in jquery suggestion please.
It looks function error in javascript and function no clear and reset option. but function show display block wrong position .
<script>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function(e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()">
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()">
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()">
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);">
<input type="text" id="number" value="">
</form>
<a id="showdatacheckbox"></a>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function (e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
if (val > 20 && val < 40) {
$("input[type='checkbox']:checked").click();
}
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()" />
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()" />
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()" />
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);" />
<input type="text" id="number" value="" />
</form>
<a id="showdatacheckbox"></a>
I would like rewrite a dom document just once.
Html:
<body>
<form id="test">
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<td width="30%">?</td>
<td>
<input name="q1" type="checkbox" id="q1" value="R"/>
R
<input name="q1" type="checkbox" id="q1" value="T"/>
T
<input name="q1" type="checkbox" id="q1" value="Ra"/>
Ra
<input name="q1" type="checkbox" id="q1" value="Ho"/>
Ho
<input name="q1" type="checkbox" id="q1" value="F"/>
F
<input name="q1" type="checkbox" id="q1" value="Fr"/>
Fr
<input name="q1" type="checkbox" id="q1" value="Fo"/>
Fo
</td>
</tr>
</table>
<br/>
<input name="submit" type="button" onClick="gradeTest()" value="Com"/>
</form>
</body>
I tried with this:
function gradeTest() {
var a1 = document.getElementsByName('q1');
var a1answers = new Array();
var a1right = new Array('R','T','Ra');
var a1bool = true;
for(i = 0; i < a1.length; i++) {
if(a1[i].checked) {
a1answers.push(a1[i].value);
}
}
a1answers.sort();
a1right.sort();
if(a1answers.length == a1right.length) {
for(i = 0; i < a1answers.length; i++) {
if(a1answers[i] != a1right[i]) {
a1bool = false;
break;
}
}
}
else {
a1bool = false;
}
if(a1bool == true) {
var moveable = document.getElementById('test');
var s = '<p align="center"> <img border=0 src="arbol.png" width="250" /></p>';
var div = document.createElement('div');
div.innerHTML = s;
var elements = div.firstChild;
document.body.appendChild(elements);
var newParent = document.body.appendChild(document.createElement('test'));
newParent.removeChild(newParent.firstChild);
newParent.insertBefore(moveable, newParent.firstChild);
correctAnswers++;
}
}
When I execute this code, print a lot of images, but i want one.
In the line 6, i put test whiout test didn't work
Thank you
Check whether you've already appended the new element, and don't add it again.
if(a1bool == true) {
if (!document.getElementById("arbol")) {
var s = '<p align="center" id="arbol"> <img border=0 src="arbol.png" width="250" /></p>';
var div = document.createElement('div');
div.innerHTML = s;
var elements = div.firstChild;
document.body.appendChild(elements);
}
correctAnswers++;
}
Why this code is not returning the value.When I click Calculate, it does not work.
Comparison is ==
Assignment is =.
You need ageNumerical = 0;
Check out this fiddle.
Here is the snippet.
function getValue() {
var a = patientAge();
var b = patientBmi();
var c = history();
var d = patientDiet();
var totalValue;
totalValue = a + b + c + d;
document.getElementById('message').innerHTML = totalValue;
}
function patientAge() {
var age = document.getElementsByName('ageRange');
var ageBracket;
var ageNumerical;
for (var i = 0; i < age.length; i++) {
if (age[i].checked) {
ageBracket = age[i].value;
}
}
if (ageBracket == "1-25") {
ageNumerical = 0;
} else if (ageBracket == "26-40") {
ageNumerical = 5;
} else if (ageBracket == "41-60") {
ageNumerical = 8;
} else {
ageNumerical = 10;
}
return ageNumerical;
}
function patientBmi() {
var bmi = document.getElementsByName('bmiRange');
var bmiValue;
var bmiNumerical;
for (var i = 0; i < bmi.length; i++) {
if (bmi[i].checked) {
bmiValue = bmi[i].value;
}
}
if (bmiValue == "0-25") {
bmiNumerical = 0;
} else if (bmiValue == "26-30") {
bmiNumerical = 0;
} else if (bmiValue == "31-35") {
bmiNumerical = 9;
} else {
bmiNumerical = 10;
}
return bmiNumerical;
}
function history() {
var patientHistory = document.getElementsByName('familyHistory');
var historyAnswer;
var historyNumerical;
for (var i = 0; i < patientHistory.length; i++) {
if (patientHistory[i].checked) {
historyAnswer = patientHistory[i].value;
}
}
if (historyAnswer == "No") {
historyNumerical = 0;
} else if (historyAnswer == "Grandparent") {
historyNumerical = 7;
} else if (historyAnswer == "Sibling") {
historyNumerical = 15;
} else {
historyNumerical = 15;
}
return historyNumerical;
}
function patientDiet() {
var dietQuestion = document.getElementsByName('dietHabits');
var dietAnswer;
var dietNumerical;
for (var i = 0; i < dietQuestion.length; i++) {
if (dietQuestion[i].checked) {
dietAnswer = dietQuestion[i].value;
}
}
if (dietAnswer == "Low sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Normal sugar") {
dietNumerical = 0;
} else if (dietAnswer == "Quite high sugar") {
dietNumerical = 7;
} else {
dietNumerical = 10;
}
return dietNumerical;
}
<div id="ageQuestion">
<p>How old are you?</p>
<label for="age1">1-25</label>
<input type="radio" name="ageRange" value="1-25" />
<label for="age2">26-40</label>
<input type="radio" name="ageRange" value="26-40" />
<label for="age3">41-60</label>
<input type="radio" name="ageRange" value="41-60" />
<label for="age4">60+</label>
<input type="radio" name="ageRange" value="60+" />
</div>
<div id="bmi">
<p>What is your BMI?</p>
<label for="bmiLevel">0-25</label>
<input type="radio" name="bmiRange" value="0-25" />
<label for="bmiLevel">26-30</label>
<input type="radio" name="bmiRange" value="26-30" />
<label for="bmiLevel">31-35</label>
<input type="radio" name="bmiRange" value="31-35" />
<label for="bmiLevel">35+</label>
<input type="radio" name="bmiRange" value="35+" />
</div>
<div id="family">
<p>Does anybody in your family have Diabetes?</p>
<label for="history">No</label>
<input type="radio" name="familyHistory" value="No" />
<label for="history">Grandparent</label>
<input type="radio" name="familyHistory" value="Grandparent" />
<label for="history">Sibling</label>
<input type="radio" name="familyHistory" value="Sibling" />
<label for="history">Parent</label>
<input type="radio" name="familyHistory" value="Parent" />
</div>
<div id="diet">
<p>How would you describe your diet?</p>
<label for="diet">Low sugar</label>
<input type="radio" name="dietHabits" value="Low sugar" />
<label for="diet">Normal sugar</label>
<input type="radio" name="dietHabits" value="Normal sugar" />
<label for="diet">Quite high sugar</label>
<input type="radio" name="dietHabits" value="Quite high sugar" />
<label for="diet">High sugar</label>
<input type="radio" name="dietHabits" value="High sugar" />
</div>
<button onclick="getValue()">Calculate</button>
<p id="message"></p>
Change == to = when assigning values.
ageNumerical == 0;
to
ageNumerical = 0;
I have the following code. I need to see how many checkboxes have been checked in my form and if there are 4 or less submit the form and if there are more display an error and don't submit.
function SetHiddenFieldValue()
{
var checks = document.getElementById('toppings').getElementsByTagName('input');
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var totalChecked = 0;
var itemPrice = 5.99;
for (i = 0; i < checks.length; i++)
{
if (checks[i].checked)
{
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
}
And my form is:
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<input type="submit" name="my-add-button" value=" add " />
</form>
any help would be appreciated.
Your javascript looks correct. I think the only you should need to do is return false; on your if (totalChecked > 4) statement.
Edit: Here's the section of your javascript function to modify:
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
} else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
Your function needs to return false to cancel the submission or true to proceed. That's why your onsubmit form attribute is set to "return XXX()" rather than just "XXX()"
As mentioned, you should return false from your check function to cancel the submit, and true if the check is okay.
How about something like this?
<html>
<head>
<title>Pizza Order Form</title>
</head>
<body>
<script>
function SetHiddenFieldValue() {
var totalChecked = 0;
var itemPrice = 5.99;
var toppings = new Array();
var randomNumber = Math.floor((Math.random() * 9000) + 100);
var checks = document.getElementsByName('topping');
for (i = 0; i < checks.length; i++) {
if (checks[i].checked) {
toppings[i] = checks[i].value;
totalChecked += 1;
}
}
if (totalChecked > 4) {
alert("You can only choose up to Max of 4 Toppings");
return false;
}
else {
itemPrice = itemPrice + (totalChecked * 0.99);
document.getElementById('my-item-name').value = toppings.join("\t");
document.getElementById('my-item-id').value = randomNumber;
document.getElementById('my-item-price').value = itemPrice;
return true;
}
}
</script>
<form id="pizza" name="pizza" method="post" action="" class="jcart" onsubmit="return SetHiddenFieldValue();">
<input type="hidden" name="my-item-id" id="my-item-id" value="" />
<input type="hidden" name="my-item-name" id="my-item-name" value="" />
<input type="hidden" name="my-item-price" id="my-item-price" value="" />
<input type="hidden" name="my-item-qty" value="1" />
<div id="toppings">
<input type="checkbox" name="topping" id="pepperoni" />Pepperoni
<input type="checkbox" name="topping" id="tomato" />Tomato
<input type="checkbox" name="topping" id="mushrooms" />Mushrooms
<input type="checkbox" name="topping" id="peppers" />Peppers
<input type="checkbox" name="topping" id="olives" />Olives
</div>
<input type="submit" name="my-add-button" value=" Add " />
</form>
</body>
</html>