JavaScript - Flawed Calculator Using Google as Example - javascript

As you can see on Google conversion at: Here
When you click the second drop down box and choose meters, Instead of it staying at 12 meters, it converts to .3048 meters, which isn't what I want. I want it so that when you change to meters on the right drop down box, it stays as 12 meters and the box on the left updates to 39.3701 feet. Here is my code so far.
var units = [['Inches', 0.025400000000000], ['Feet', 0.30480000000000000], ['Furlongs', 201.168], ['Meters', 1.00]];
var selectors = document.querySelectorAll('.newClass1');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
function calcLength1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function calcLength2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}
Here is my HTML:
<div class="panel">
<p>From:</p>
<select style="float:left" id="lengthCalc1" class="js-example-basic-single select2-container newClass1" oninput="calcLength2()" onchange="calcLength2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput1" type="number" oninput="calcLength1()" />
<p>To:</p>
<select style="float:left" id="lengthCalc2" class="js-example-basic-single select2-container newClass1" oninput="calcLength1()" onchange="calcLength1()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput2" type="number" oninput="calcLength2()" onchange="calcLength2()" />
</div>
It's completely flawed. Please help me make a good calculator.

Update: To make the converter function properly same as the google length converter, you can try the following:
Update the second input box value when either of the of the dropdown of units changes.
Update the first input box when the second input box is changed, and vice-versa.
This means, your first input box value will update only when the user changes the value of the second input. Try it on the google's converter, it behaves the same way.
Use the following code to make it work.
var units = [
['Inches', 0.025400000000000],
['Feet', 0.30480000000000000],
['Furlongs', 201.168],
['Meters', 1.00]
];
var selectors = document.querySelectorAll('.newClass1');
for (var i = 0; i < units.length; i++) {
for (var j = 0; j < selectors.length; j++) {
var option = document.createElement('option');
option.value = units[i][1];
option.textContent = units[i][0];
selectors[j].add(option);
}
}
function updateInputBox2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function updateInputBox1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}
<div class="panel">
<p>From:</p>
<select style="float:left" id="lengthCalc1" class="js-example-basic-single select2-container newClass1" oninput="updateInputBox2()" onchange="updateInputBox2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput1" type="number" oninput="updateInputBox2()" />
<p>To:</p>
<select style="float:left" id="lengthCalc2" class="js-example-basic-single select2-container newClass1" oninput="updateInputBox2()" onchange="updateInputBox2()">
</select>
<input style="height:50%;font-size:15pt;width:1000px; border: 1px solid #000;" id="lengthInput2" type="number" oninput="updateInputBox1()" onchange="updateInputBox1()" />
</div>
First problem with the conversion (outdated)
Convert the values to number correctly and it should work. You have few typos in your code and also there's a left hand assignment error. Look at this line in your code, there are two errors:
parseFloat(document.getElementById("lengthInput2").value) = praseFloat(SpecialValue);
Try this, it should work.
function calcLength1() {
var SpecialValue = parseFloat(document.getElementById("lengthInput1").value) * parseFloat(document.getElementById("lengthCalc1").value) / parseFloat(document.getElementById("lengthCalc2").value);
document.getElementById("lengthInput2").value = SpecialValue;
}
function calcLength2() {
var SpecialValue = parseFloat(document.getElementById("lengthInput2").value) * parseFloat(document.getElementById("lengthCalc2").value) / parseFloat(document.getElementById("lengthCalc1").value);
document.getElementById("lengthInput1").value = SpecialValue;
}

Related

Multiplying the number by the value pass in select option when click + in input type number

I'm trying to multiply value pass from input tag type number by value pass from select tag.
<div>
<input type="number" value="0" id="input" name="word_count" value="500" style="text-align: center;" />
<select id="work" onchange="myFunction();" name="work">
<option>-Select-</option>
<option value="article">Article</option>
</select>
</div>
function myFunction() {
var x = document.getElementById("work").value;
if (document.getElementById("work").value == "article") {
var w = 5;
if (document.getElementById("input")) {
var x = document.getElementById("input").value;
var wc = w * x;
document.getElementById("total_amount").value = +wc;
document.getElementById("np").value = +wc;
}
}
}
You didn't have tags with id total_amount and np. I added them to the HTML. (I added <span></span> tags, so I changed the value to textContent at the end of the conditional)
You redeclared var x (and redefined it) in your conditional - I renamed it to z (it might not have caused a problem, but just to be sure). Actually if you'd done it with the let keyword, it would've thrown an exception).
function myFunction() {
var x = document.getElementById("work").value;
console.log(x)
if (document.getElementById("work").value == "article") {
var w = 5;
if (document.getElementById("input")) {
// renamed x to z
var z = document.getElementById("input").value;
var wc = w * z;
// not .value but .textContent
document.getElementById("total_amount").textContent = +wc;
document.getElementById("np").textContent = +wc;
}
}
}
<div>
<input type="number" value="0" id="input" name="word_count" value="500" style="text-align: center;" />
<select id="work" onchange="myFunction();" name="work">
<option disabled selected>-Select-</option>
<option value="article">Article</option>
</select>
</div>
Total amount: <span id="total_amount"></span><br /> NP: <span id="np"></span>

Quantity in Inches to Convert to Feet, Centimeters or Yards Javascript

The instructions goes as follows:
Ask the user to enter a quantity in inches (in a textbox).
Have a select box with options for: Feet, Centimeters, Yards.
If they chose inches, calculate the conversion as 1 inch = 0.0833 feet. For Centimeters: 1 inch = 2.54 centimeters. For Yards, 1 inch = 0.02778.
Because the user may enter a decimal amoung (e.g. 3.99), be sure to parse using the parseFloat option.
Using a reference: Look up the toFixed() function and make sure that your result is outputted to 2 decimal places.
Output to a div section called results. Output using the innerHTML command.
This is the code that I currently have in place
function convertCurrency(r) {
document.getElementById("cnvrtMoney").innerHTML = "output";
if (dropdown == "feetConversion".parseFloat(r)) {
Convert = Convert / 0.0833;
} else if (dropdown == "centimetersConversion".parseFloat(r)) {
Convert = Convert / 2.54;
} else if (dropdown == "yardsConversion".parseFloat(r)) {
Convert = Convert / 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be" + Convert;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form action="CurrencyConverter.php" method="get">
Enter Quantity (In Inches): <input type="text" name="inputInches" /><br> Select Conversion:
<select name="dropdown">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
</form>
</div>
<div id="results">
</div>
</body>
</html>
I'm trying to make it display once the user clicks on the dropdown button with the exact conversion that it needs to be. If anyone could help I would greatly appreciate it.
First, this is JavaScript code, you do not need <form>.
Second, to access elements by ID you have to set ID attribute instead of NAME.
Third, math is wrong.
Forth...
It's better to show working code. This is event handler:
function convertCurrency() {
var dropdown = document.getElementById("dropdown").value;
var inputInches = document.getElementById("inputInches").value;
switch (dropdown){
case "feetConversion":
Convert = inputInches * 0.0833;
break;
case "centimetersConversion":
Convert = inputInches * 2.54;
break;
case "yardsConversion":
Convert = inputInches * 0.02778;
break;
}
var resultsString = "The amount would be: " + Convert;
document.getElementById("results").innerHTML = resultsString;
}
This is HTML layout:
<input type="text" id="inputInches"/><br>
Select Conversion:
<select id="dropdown" onchange="convertCurrency()">
<option value="" disabled="disabled" selected="selected"></option>
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<div id="results"></div>
http://jsfiddle.net/ArtyomShegeda/xbj5pf62/13/
You never call convertCurrency. You need an event listener that calls it. You could put a "Convert" button in the form, and call it when they click on the button.
Code like if (dropdown == "feetConversion".parseFloat(r)) makes no sense. parseFloat() is a global function, it's not a method of a string. You just want to compare dropdown to the string. parseFloat should be used to set the Convert variable at the beginning of the function.
You don't need an action or method in a form that's being processed in JavaScript, not the server.
You never set the value of dropdown. You need to get that from the value of the dropdown. I added an ID to it, and get that using document.getElementById("selectConversion").value
There's no element cnvrtMoney. I'm not sure what the point of document.getElementById("cnvrtMoney").innerHTML = "output"; is supposed to be. I've removed it.
Your conversions are all wrong, you're dividing when you should be multiplying.
function convertCurrency(r) {
var dropdown = document.getElementById("selectConversion").value;
var Convert = parseFloat(r);
if (dropdown == "feetConversion") {
Convert = Convert / 12;
} else if (dropdown == "centimetersConversion") {
Convert = Convert * 2.54;
} else if (dropdown == "yardsConversion") {
Convert = Convert / 36;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
document.getElementById("convertButton").addEventListener("click", function() {
convertCurrency(document.getElementById("inputInches").value);
});
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter {
background-color: white;
text-align: center;
text-justify: auto;
}
#EndResults {
background-color: darkgray;
text-align: center;
}
<html>
<head>
<meta charset="utf-8">
<title>Assignment 01: Currency Converter</title>
</head>
<body>
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<form>
Enter Quantity (In Inches): <input type="text" name="inputInches" id="inputInches" /><br> Select Conversion:
<select name="dropdown" id="selectConversion">
<option value="feetConversion">Feet </option>
<option value="centimetersConversion">Centimeters </option>
<option value="yardsConversion">Yards </option>
</select>
<br>
<input type="button" value="Convert" id="convertButton">
</form>
</div>
<div id="results">
</div>
</body>
</html>
Ok, I had to rewrite the entire thing, but here it is
function convertCurrency(r) {
let c = document.getElementById('q').value;
let v = document.getElementById('c').value;
switch(v){
case "feet":
result = c / 0.0833;
break;
case "cent":
result = c / 2.54;
break;
case "yard":
result = c /0.02778;
break;
}
result = result.toFixed(2);
var resultsString = "The amount would be " + result;
document.getElementById('results').innerHTML = resultsString;
}
body {
background-color: gray;
}
#heading {
background-color: lightgray;
text-align: center;
}
#formConverter{
background-color: white;
text-align: center;
text-justify:auto;
}
#results{
background-color:darkgray;
text-align: center;
}
<div id="heading">
<h1> Currency Converter </h1>
<img src="CurrencyConverter.jpg" alt="Currency Converter Banner" width="600" height="200">
</div>
<div id="formConverter">
<p>
Enter Quantity (in inches):
<input type="number" id="q" name="q">
</p>
<p>
Select conversion:
<select id="c" name="c">
<option value="feet">Feet</option>
<option value="cent">Centimeters</option>
<option value="yard">Yards</option>
</select>
</p>
<button onclick="convertCurrency()">
Convert
</button>
</div>
<div id="results">
</div>
There's a lot needing to be fixed here, but changing the contents of your script tag to the following should work:
<script>
window.onload = function() {
var form = document.getElementById( "convert-input" );
form.getElementsByTagName( "select" )[ 0 ].addEventListener( "input", function(){
convertCurrency( this.value, form.getElementsByTagName( "input" )[ 0 ].value );
}, true );
}
function convertCurrency( dropdown, r) {
if (dropdown == "feetConversion"){
Convert = parseFloat(r) * 0.0833;
}
else if (dropdown == "centimetersConversion"){
Convert = parseFloat(r) * 2.54;
}
else if (dropdown == "yardsConversion"){
Convert = parseFloat(r) * 0.02778;
}
Convert = Convert.toFixed(2);
var resultsString = "The amount would be " + Convert;
document.getElementById('results').innerHTML = resultsString;
}
</script>
Note that your conversions were incorrect as you had chosen a scaling factor that needed multiplication

Preset dropdown for HTML form?

I am trying to make a HTML form with a preset dropdown. The form is meant to be used frequently, so the preset menu is supposed to help the user choose common input options.
I cannot find any tutorials on how to do this anywhere, so I was hoping someone could point me in the right direction. I do not want to use any external libraries, if possible.
By a preset dropdown, I mean something like this:
var lastPreset = "preset1";
function previousPreset(element) {
lastPreset = element.value;
}
function updatePresets(element) {
var old = document.getElementById(lastPreset);
if (old) {
old.style.display = "none";
for (var i = 0; i < old.childNodes.length; i++) {
old.childNodes[i].required = false;
}
}
var preset = element.value;
var div = document.getElementById(preset);
if (div) {
div.style.display = "block";
for (var i = 0; i < div.childNodes.length; i++) {
div.childNodes[i].required = true;
}
}
lastPreset = preset;
}
function submitted() {
console.log("Submitted!");
return false;
}
#preset2, #preset3 {
display: none;
}
<form onsubmit="return submitted();">
<select onchange="updatePresets(this);" onfocus="previousPreset(this);">
<option selected value="preset1">Preset 1</option>
<option value="preset2">Preset 2</option>
<option value="preset3">Preset 3</option>
</select>
<div id="preset1">
<textarea required placeholder="Sample Text"></textarea>
</div>
<div id="preset2">
<input type="text">
</div>
<div id="preset3">
<input type="file">
</div>
<input type="submit" value="Submit">
</form>
This is just a hacky mess I made in a few minutes to show the sort of behaviour that I am trying to achieve. I am just looking for any tutorials or guides on how to do this sort of thing. It seems like someone would have tried this before.
Thanks for any responses!
I found out a far better method involving classes from looking at similar answers:
function updatePresets(element) {
var presets = document.getElementsByClassName("presets");
var div = document.getElementById(element.value);
for (var i = 0; i < presets.length; i++) {
var preset = presets[i];
preset.style.display = div === preset ? "block" : "none";
for (var j = 0; j < preset.childNodes.length; j++) {
preset.childNodes[j].required = div === preset;
}
}
}
function submitted() {
console.log("Submitted!");
return false;
}
#preset2, #preset3 {
display: none;
}
<form onsubmit="return submitted();">
<select onchange="updatePresets(this);">
<option selected value="preset1">Preset 1</option>
<option value="preset2">Preset 2</option>
<option value="preset3">Preset 3</option>
</select>
<div id="preset1" class="presets">
<textarea required placeholder="Sample Text"></textarea>
</div>
<div id="preset2" class="presets">
<input type="text">
</div>
<div id="preset3" class="presets">
<input type="file">
</div>
<input type="submit" value="Submit">
</form>

adding option to a select in JavaScript not updating

the select option will not update till i add the innerHTML again.
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
i am stepping thorugh multiple input fields and gathering the values, these are then added to a new option element. when i appendChild to the selectaccount2 which is the select element, this does not insert the value. any ideas?
<!-- Text input-->
<div id="details" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="accountNumber">Account Number</label>
<div class="col-md-4">
<input id="accountNumber" name="accountNumber" type="text" placeholder="your game account number" class="form-control input-md" required="" onchange="myFunction()">
</div>
</div>
</div>
<div id="DetailsFooter" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">details</label>
<div class="col-md-4">
<select id="AccountToUse" name="AccountToUse" type="text" placeholder="" required="">
</select>
</div>
</div>
</div>
<fieldset id="DetailsView" class="DetailsView">
<h2>Details Applicant 1</h2>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="Accounts">How many accounts do you have?</label>
<div class="col-md-4">
<select id="Accounts" name="Accounts" class="form-control" onchange="amountchanged()">
<option value="0">Please Select an Amount</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
<div id="DetailsContainer">
</div>
</fieldset>
<script>
var select = document.getElementById("Accounts"),
container = document.getElementById("DetailsContainer");
var array = [];
var accountToUse;
var footer;
var num = 0;
function changeId(nodes, n) {
for (var i = 0; i < nodes.length; i = i + 1) {
if (nodes[i].childNodes) {
changeId(nodes[i].childNodes, n);
}
//if id value is 'accountNumber', change it
if (nodes[i].id && /^ch$|^accountNumber$/i.test(nodes[i].id)) {
nodes[i].id += String(n);
array.push(nodes[i]);
}
}
}
function amountchanged() {
var amount = select.value,
obj = document.getElementById("details").cloneNode(true),
children = obj.childNodes;
footer = document.getElementById("DetailsFooter");
container.innerHTML = "";
var count;
num += 1;
obj.id = obj.id + num;
if (num < 16) {
changeId(children, num);
}
document.body.appendChild(obj);
for (count = 1; count <= amount; count++) {
var heading = "<h3>" + count + " Details</h3>"
container.innerHTML += heading;
container.innerHTML += obj.innerHTML;
}
accountToUse = footer.getElementsByTagName("select")[0];
accountToUse.id = 'AccountToUse1';
container.innerHTML += footer.innerHTML;
}
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var select22 = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = select22.value;
opt.innerHTML = select22.value;
select.value = "test";
selectaccount2.appendChild(opt);
}
}
</script>
Although I've seen people recommend adding an option the way you have there, so presumably it works on many if not most browsers, the most robust, reliable way I've ever found is the Option constructor and the add method:
selectaccount2.options.add(new Option(selectban.value));
If you just provide the value (the first argument), the text and value will be the same. If you give two arguments, the first is the text and the second is the value.
Live copy:
var array = [{
id: "one"
}, {
id: "two"
}, {
id: "three"
}];
function myFunction() {
for (var index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
myFunction();
<select id="AccountToUse1" size="4"></select>
<input type="hidden" id="one" value="uno">
<input type="hidden" id="two" value="due">
<input type="hidden" id="three" value="tre">
Side note: You're falling prey to The Horror of Implicit Globals: Declare index.

Calculating the value of radio buttons, select and check boxes

HI I am doing a menu for a pizza place (Leaning project) where one the user select the radio buttons the the select buttons it calculations the total. Instance at the minute I a chose of three radio buttons small medium and large. and 3 select boxes. each time select box is chosen £1 will be added to the price of the given value of the chosen radio button. For instance if some selects the small radio button that's £4 then they select the next three select box's that's a total of £7 which should be displayed instantly on the screen on each selection. I haven't added the check boxes yet as I have noticed its not working. I got the original script from an on-line tutorial that worked when I tested. But after tying to modify it to suit it seems that the dive that displays the total price wont work.
< body onload = 'hideTotal()' >
< div id = "wrap" >
< form action = ""
id = "pizzaform"
onsubmit = "return false;" >
< div >
< div class = "cont_order" >
< fieldset >
< legend > Make your Pizza! < /legend>
<label >Size Of the Pizza</label > < br / >
Small Pizza 7 "(£4)
<label class='radiolabel'><input type="
radio " name="
selectedpizza " value="
Round1 " onclick="
calculateTotal()
" />Round </label><br />
Large 11" (£6) < label class = 'radiolabel' > < input type = "radio"
name = "selectedpizza"
value = "Round2"
onclick = "calculateTotal()" / > Round < /label><br / >
Midum 15 "(£8)
<label class='radiolabel'><input type="
radio " name="
selectedpizza " value="
Round3 " onclick="
calculateTotal()
" />Round </label><br />
<br />
<label >Sacuce</label>
<select id="
sauce " name='sauce' onchange="
calculateTotal()
">
<option value="
None ">Select Sacuce</option>
<option value="
Enzo 's classic Sauce">Enzo'
s classic Sauce(£1) < /option>
<option value="Spicy Tomato">Spicy Tomato(£1)</option >
< /select>
<br / >
< label > Base < /label>
<select id="base" name='base' onchange="calculateTotal()">
<option value="None">Select Base</option >
< option value = "Thin and cripy" > Thin and cripy(£1) < /option>
<option value="Deep Pan">Deep Pan(£1)</option >
< option value = "Stuffed Crust" > Stuffed Crust(£1) < /option>
</select >
< br / >
< label > Cheese < /label>
<select id="cheese" name='cheese' onchange="calculateTotal()">
<option value="None">Select cheese</option >
< option value = "Mozzarella" > Mozzarella(£1) < /option>
<option value="Reduced Fat">Reduced Fat(£1)</option >
< /select>
<br / >
< div id = "totalPrice" > < /div>
</fieldset >
< /div>
</div >
< /form>
</div > <!--End of wrap-->
< script language = "javascript"
type = "text/javascript" >
/*
This source is shared under the terms of LGPL 3
www.gnu.org/licenses/lgpl.html
You are free to use the code in Commercial or non-commercial projects
*/
//Set up an associative array
//The keys represent the size of the Pizza
//The values represent the cost of the Pizza i.e A 15" Pizza cost's £8
var pizza_prices = new Array();
pizza_prices["Round1"] = 4;
pizza_prices["Round2"] = 6;
pizza_prices["Round3"] = 8;
var sacuce_prices = new Array();
sacuce_prices["None"] = 0;
sacuce_prices["Enzo's classic Sauce"] = 1;
sacuce_prices["Spicy Tomato"] = 1;
var base_prices = new Array();
base_prices["None"] = 0;
base_prices["Thin and cripy"] = 1;
base_pricess["Deep Pan"] = 1;
base_pricess["Stuffed Crust"] = 1;
var cheese_prices = new Array();
cheese_prices["None"] = 0;
cheese_prices["Mozzarella"] = 1;
cheese_prices["Reduced Fat"] = 1;
// getPizzaSizePrice() finds the price based on the size of the Pizza.
// Here, we need to take user's the selection from radio button selection
function getPizzaSizePrice() {
var pizzaSizePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the Pizza the user Chooses name=selectedPizza":
var selectedPizza = theForm.elements["selectedpizza"];
//Here since there are 4 radio buttons selectedPizza.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedPizza.length; i++) {
//if the radio button is checked
if (selectedPizza[i].checked) {
//we set PizzaSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" Pizza we set it to 6
//by using the pizza_prices array
//We get the selected Items value
//For example pizza_prices["Round2".value]"
pizzaSizePrice = pizza_prices[selectedPizza[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the PizzaSizePrice
return PizzaSizePrice;
}
function getPizzaSacucePrice() {
var pizzaSaucePrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="sauce"
var selectedSauce = theForm.elements["sauce"];
//set pizzaSauce Price equal to value user chose
//For example sauce_prices
pizzaSaucePrice = sauce_prices[selectedSauce.value];
//finally we return pizzaSaucePrice
return PizzaSaucePrice;
}
function getBasePrice() {
var pizzaBasePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="base"
var selectedBauce = theForm.elements["base"];
//set pizzaBase Price equal to value user chose
//For example base_prices
pizzaBaseePrice = base_prices[selectedBase.value];
//finally we return pizzaSaucePrice
return pizzaBasePrice;
}
function getCheesePrice() {
var pizzaCheesePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="cheese"
var selectedCheese = theForm.elements["cheese"];
//set pizzaCheese Price equal to value user chose
//For example cheese_prices
pizzaBaseePrice = cheese_prices[selectedSauce.value];
//finally we return pizzaCheesePrice;
return PizzaCheesePrice;
}
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var pizzaPrice = getPizzaSizePrice() + getSacucePrice() + getBasePrice() + getCheesePrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price For the Pizza £" + pizzaPrice;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
< /script>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="pizzaform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Make your Pizza!</legend>
<label>Size Of the Pizza</label>
<br />Small Pizza 7"(£4)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round1" onclick="calculateTotal()" />Round</label>
<br />Large 11"(£6)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round2" onclick="calculateTotal()" />Round</label>
<br />Midum 15"(£8)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round3" onclick="calculateTotal()" />Round</label>
<br />
<br />
<label>Sacuce</label>
<select id="sauce" name='sauce' onchange="calculateTotal()">
<option value="None">Select Sacuce</option>
<option value="Enzo's classic Sauce">Enzo's classic Sauce(£1)</option>
<option value="Spicy Tomato">Spicy Tomato(£1)</option>
</select>
<br />
<label>Base</label>
<select id="base" name='base' onchange="calculateTotal()">
<option value="None">Select Base</option>
<option value="Thin and cripy">Thin and cripy(£1)</option>
<option value="Deep Pan">Deep Pan(£1)</option>
<option value="Stuffed Crust">Stuffed Crust(£1)</option>
</select>
<br />
<label>Cheese</label>
<select id="cheese" name='cheese' onchange="calculateTotal()">
<option value="None">Select cheese</option>
<option value="Mozzarella">Mozzarella(£1)</option>
<option value="Reduced Fat">Reduced Fat(£1)</option>
</select>
<br />
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
Can any one help? Also I plan on give the user a choice of 10 toppings using check boxes is there a way of limiting the user so they can only choose 4 out of the choice of 10?
Data attributes would work well for both purposes.
Counting the total
Use data-price on radios, checkboxes and options:
<form id="my-form">
<input type="radio" data-price="100" name="radio">Add 1GBP
<input type="radio" data-price="200" name="radio">Add 2GBP
<select>
<option>Select something</option>
<option data-price="300">Add 3GB</option>
<option data-price="400">Add 4GB</option>
</select>
</form>
Total: <span id="my-total"></span>
Then count them on every page load and form change with jQuery:
$('#my-form').on('change', function(){
update_total();
});
function update_total(){
var tot = 0;
var price = 0;
$('#my-form input:checked').each(function(){
price = $(this).data('price');
if(price > 0){
tot += price;
}
});
$('#my-form select').each(function(){
price = $("option:selected", this).data('price');
if(price > 0){
tot += price;
}
});
$('#my-total').html(tot);
}
update_total();
Limiting checkboxes
Use data-max-check to define the maximum amount of checkboxes that can be checked in a given container:
<div data-max-check="4">
<input type="checkbox">
<input type="checkbox">...
Then stop the user from selecting more than the maximum with jQuery:
$('[data-max-check] input[type=checkbox]').on('click', function(e){
var $parent = $(this).closest('[data-max-check]');
var max = $parent.data('max-check');
var chk = $parent.find('input[type=checkbox]:checked').size();
if(chk > max){
alert('You can only select up to ' + max);
e.preventDefault();
}
});
Demo
You can see both in action here: JSFiddle

Categories